我有以下Spring Boot OAuth配置。我设法在Postman中获取访问令牌,并使用用户名和密码发出以下POST请求。
localhost:8080/oauth/token?grant_type=password
With header (Authorization: Basic <base64 client_id>)
它返回一个access_token。但是,当我使用该令牌访问资源URL时,如下所示,它返回401 Unauthorized错误。
localhost:8080/api/customer
With header (Authorization : Bearer <access_token>)
以下是我的OAuth配置。
@Configuration
@EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Bean
public TokenStore tokenStore() {
return new InMemoryTokenStore();
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore());
endpoints.authenticationManager(authenticationManager);
endpoints.userDetailsService(userDetailsService);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer
.allowFormAuthenticationForClients()
.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("clientIdPassword")
.scopes("read","write", "trust")
.authorizedGrantTypes(
"password","authorization_code", "client_credentials", "refresh_token", "implicit");
}
}
我的WebSecurityConfigurerAdapter实现的相关部分如下。
@Override
protected void configure(HttpSecurity http) throws Exception {
http.headers().frameOptions().disable();
http.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS).permitAll()
.antMatchers("/auth/token").permitAll()
//.antMatchers("/**").hasAnyAuthority("ADMIN", "OPERATOR")
.anyRequest().authenticated()
.and().exceptionHandling().authenticationEntryPoint(new RESTAuthenticationEntryPoint())
.and().cors().configurationSource(corsConfigurationSource())
.and().csrf().disable()
.formLogin()
.successHandler(new RESTAuthenticationSuccessHandler(objectMapper, userDetailService))
.failureHandler(new RESTAuthenticationFailureHandler())
.and()
.logout().logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler());
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD"));
configuration.setExposedHeaders(Arrays.asList(headerName));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
@Bean
public AuthenticationTrustResolver getAuthenticationTrustResolver() {
return new AuthenticationTrustResolverImpl();
}
你能否告诉我我的代码有什么问题导致401 Unauthorized错误,即使有效的access_token也是如此。