问题
I'm using spring-security
and spring-security-oauth2
(JWT access tokens) for authentication and authorization. The idea is to let all requests through, but to be able to distinguish between authenticated users and unauthenticated users. As soon as I enable @EnableResourceServer
my configured HttpSecurity
seems to get ignored. And requests return 401:
{
"error": "unauthorized",
"error_description": "Full authentication is required to access this resource"
}
Here's the config:
@SpringBootApplication
@EnableJpaRepositories
@ComponentScan
@EntityScan
@EnableWebSecurity
public class Application {
public static void main(final String[] args) {
new SpringApplicationBuilder(Application.class).bannerMode(Banner.Mode.OFF).run(args);
}
@EnableResourceServer
public static class SecurityConfig extends WebSecurityConfigurerAdapter implements JwtAccessTokenConverterConfigurer {
@Override
protected void configure(final HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().anyRequest().permitAll();
}
@Override
public void configure(final JwtAccessTokenConverter converter) {
final DefaultAccessTokenConverter conv = new DefaultAccessTokenConverter();
conv.setUserTokenConverter(userAuthenticationConverter());
converter.setAccessTokenConverter(conv);
}
@Bean
public UserAuthenticationConverter userAuthenticationConverter() {
return new ResourceAuthenticationConverter();
}
}
回答1:
You're almost there. It's an easy fix - the javadoc of @EnableResourceServer provides the answer:
Users should add this annotation and provide a @Bean of type ResourceServerConfigurer (e.g. via ResourceServerConfigurerAdapter) that specifies the details of the resource (URL paths and resource id).
You're using a WebSecurityConfigurerAdapter
however. Just change it to ResourceServerConfigurerAdapter
and enhance the visibility of configure
:
@EnableResourceServer
public static class SecurityConfig extends ResourceServerConfigurerAdapter implements JwtAccessTokenConverterConfigurer {
// snip
@Override
public void configure(final HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().anyRequest().permitAll();
}
// snip
来源:https://stackoverflow.com/questions/43931255/spring-security-returns-401-despite-authorizerequests-anyrequest-permitall