Я пытаюсь интегрировать OAuth 2 + JWT, используя Spring Boot 2 + Netflix OSS. При запросе токена доступа я получаю приведенную ниже ошибку в Zuul Gateway, который действует как сервер ресурсов.
2019-05-04 14: 41: 29.157 ОТЛАДКА 23272 --- [nio-8765-exec-2] o.s.s.w.a.ExceptionTranslationFilter: произошло исключение аутентификации; перенаправление на точку входа аутентификации
org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: объект аутентификации не был найден в SecurityContext
Может кто-нибудь помочь и сказать, что мне не хватает в коде?
Zuul Gateway + Resource Server
@Configuration
@EnableResourceServer
@Order(value = 0)
@EnableOAuth2Sso
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/oauth/token/**").permitAll()
//.antMatchers("/login/**,/oauth/**").permitAll()
.antMatchers("/trips/**").hasAnyRole("CLIENT", "USER", "ANONYMOUS")
.and().csrf().disable()
.anonymous().disable();
}
}
application.yml
logging:
level:
org.springframework: DEBUG
server:
port: 8765
spring:
application:
name: gateway
# Map path to auth service
zuul:
routes:
trips:
path: /trips/**
url: http://localhost:1000/api/trips
rides:
path: /rides/**
url: http://localhost:1000/api/rides
mauth:
path: /oauth/**
url: http://localhost:1000/oauth
#OAuth Configurations
security:
oauth2:
client:
#access-token-uri: https://auth/login
#user-authorization-uri: /auth/oauth/authorize
accessTokenUri: http://localhost:1000/oauth/authorize
userAuthorizationUri: http://localhost:1000/oauth/token
client-id: sapepool
client-secret: sapepool
resource:
jwt:
key-uri: http://localhost:1000/oauth/token_key
#key-value:
Сервер авторизации
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Autowired
@Qualifier("customUserDetailsService")
private UserDetailsService userDetailsService;
/**
* Token store.
*
* @return the token store
*/
/*@Bean
public DatastoreTokenStore tokenStore() {
return new DatastoreTokenStore(datastoreDataSource);
}*/
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(jwtAccessTokenConverter());
}
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setKeyPair(new KeyStoreKeyFactory(new ClassPathResource("jwt.jks"), "password".toCharArray()).getKeyPair("jwt"));
converter.setSigningKey("123");
converter.setVerifierKey("123");
return converter;
}
/**
*
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager).userDetailsService(userDetailsService)
.tokenStore(tokenStore())//.tokenServices(tokenServices())
.tokenEnhancer(jwtAccessTokenConverter())
.accessTokenConverter(jwtAccessTokenConverter())
.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
}
/**
* Authorization server security Configuration.
*
* @param oauthServer
* the oauth server
* @throws Exception
* the exception
*/
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("sapepool")
.secret("{noop}sapepool")
//.secret("sapepool")
.authorizedGrantTypes("client_credentials", "password","refresh_token")
.authorities("ROLE_CLIENT", "ROLE_ANDROID_CLIENT", "ROLE_ANONYMOUS")
.scopes("read", "write", "trust")
.accessTokenValiditySeconds(5000)
.refreshTokenValiditySeconds(50000);
//.resourceIds("oauth2-resource") - isAutoApprove()
}
}
Сервер авторизации - Web Security Config
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private static Logger log = LoggerFactory.getLogger(WebSecurityConfig.class);
@Autowired
private UserDetailsService userDetailsService;
@Override
@Bean
public UserDetailsService userDetailsServiceBean() throws Exception {
return super.userDetailsServiceBean();
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/oauth/token/**").permitAll()
.anyRequest().permitAll()
//.antMatchers("*/oauth/**").permitAll()
//.antMatchers("/**").permitAll()
.and().csrf().disable();
//.anonymous().disable();
/*
* http.csrf().disable().exceptionHandling() //.authenticationEntryPoint( //
* (request, response, authException) ->
* response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
* .and().authorizeRequests().antMatchers("/**").authenticated().and().httpBasic
* ();
*/
}
@Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
}