spring尽管返回401,尽管authorizeRequests()。anyRequest()。permitAll()

时间:2017-05-12 06:58:16

标签: java spring spring-security jwt spring-oauth2

我使用spring-securityspring-security-oauth2(JWT访问令牌)进行身份验证和授权。我们的想法是让所有请求通过,但能够区分经过身份验证的用户和未经身份验证的用户。一旦启用@EnableResourceServer,我的配置HttpSecurity似乎就会被忽略。请求返回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();
        }
    }

1 个答案:

答案 0 :(得分:1)

你几乎就在那里。这是一个简单的解决方法 - javadoc of @EnableResourceServer提供了答案:

  

用户应添加此注释并提供类型的@Bean   ResourceServerConfigurer(例如,通过ResourceServerConfigurerAdapter)   指定资源的详细信息(URL路径和资源   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