创建 TokenEndpointAuthenticationFilter 实现
CustomTokenEndpointAuthenticationFilter.java
public class CustomTokenEndpointAuthenticationFilter extends TokenEndpointAuthenticationFilter {
public CustomTokenEndpointAuthenticationFilter(AuthenticationManager authenticationManager, OAuth2RequestFactory oAuth2RequestFactory) {
super(authenticationManager, oAuth2RequestFactory);
}
@Override
protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException {
/* on successful authentication do stuff here */
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
/* before authentication check for condition if true then process to authenticate */
if (!condition) {
throw new AuthenticationServiceException("condition not satisfied");
}
super.doFilter(req, res, chain);
}
}
Inside 授权服务器配置做出这些改变
@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Inject
private DataSource dataSource;
@Inject
private JHipsterProperties jHipsterProperties;
@Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
/* create OAuth2RequestFactory instance */
private OAuth2RequestFactory oAuth2RequestFactory;
@Inject
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception {
/* assign value in OAuth2RequestFactory instance */
oAuth2RequestFactory = endpoints.getOAuth2RequestFactory();
endpoints
.tokenStore(tokenStore())
.authenticationManager(authenticationManager);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
/* register TokenEndpointAuthenticationFilter with oauthServer */
oauthServer
.allowFormAuthenticationForClients()
.addTokenEndpointAuthenticationFilter(new CustomTokenEndpointAuthenticationFilter(authenticationManager, oAuth2RequestFactory));
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.inMemory()
.withClient(jHipsterProperties.getSecurity().getAuthentication().getOauth().getClientid())
.scopes("read", "write")
.authorities(AuthoritiesConstants.ADMIN, AuthoritiesConstants.USER)
.authorizedGrantTypes("password", "refresh_token", "authorization_code", "implicit")
.secret(jHipsterProperties.getSecurity().getAuthentication().getOauth().getSecret())
.accessTokenValiditySeconds(jHipsterProperties.getSecurity().getAuthentication().getOauth().getTokenValidityInSeconds());
}
}