spring-security returns 401 尽管 authorizeRequests().anyRequest().permitAll()

spring-security returns 401 despite authorizeRequests().anyRequest().permitAll()

我正在使用 spring-securityspring-security-oauth2(JWT 访问令牌)进行身份验证和授权。这个想法是让所有请求通过,但能够区分经过身份验证的用户和未经身份验证的用户。一旦启用 @EnableResourceServer,我配置的 HttpSecurity 似乎就会被忽略。并请求 return 401:

{
    "error": "unauthorized",
    "error_description": "Full authentication is required to access this resource"
}

配置如下:

@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();
        }
    }

你快到了。这是一个简单的修复 - javadoc of @EnableResourceServer 提供了答案:

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).

但是您使用的是 WebSecurityConfigurerAdapter。只需将其更改为 ResourceServerConfigurerAdapter 并提高 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