【问题标题】:spring-security returns 401 despite authorizeRequests().anyRequest().permitAll()尽管 authorizeRequests().anyRequest().permitAll() spring-security 返回 401
【发布时间】:2017-10-11 09:23:28
【问题描述】:

我正在使用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();
        }
    }

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2020-07-24
      • 2021-05-21
      • 2023-01-11
      • 2019-03-25
      • 2018-03-27
      • 2018-04-26
      • 2019-03-10
      • 2020-08-26
      • 2018-11-06
      相关资源
      最近更新 更多