【问题标题】:Spring Security with Spring Boot: Allowing unauthenticated user access on specific endpoints when using a filterSpring Security with Spring Boot:使用过滤器时允许未经身份验证的用户访问特定端点
【发布时间】:2017-04-17 02:24:01
【问题描述】:

我正在努力学习 Spring Security 的基础知识。

我希望达到的目标

我的系统仅用于 REST API 处理,/user/sign_in 上有一个登录端点 POST 和一些开放端点 - /prompt/, /prompt/{id}, /story/, /story/{id} 上的 GET,其余所有内容仅适用于经过身份验证的用户。


我有一个自定义身份验证过滤器,已放在BasicAuthenticationFilter 之前。我在这里分享我的 WebSecurityConfigurerAdapter 代码

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DemoAuthenticationProvider demoAuthenticationProvider;

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .antMatchers(HttpMethod.GET, "/version", "/story", "/prompt").permitAll()
                .antMatchers(HttpMethod.POST, "/user/sign_in").permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilterBefore(new DemoAuthenticationFilter(), BasicAuthenticationFilter.class);
        http.csrf().disable();
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(demoAuthenticationProvider);
    }
}

对于开放端点的匿名用户,我在过滤器中返回一个空身份验证令牌,我得到了

403 访问被拒绝

当我提到允许所有而不是仅对这些端点进行身份验证时,为什么需要身份验证令牌?以及如何正确实施它?

【问题讨论】:

    标签: spring rest authentication spring-security spring-boot


    【解决方案1】:

    我的错!

    spring-boot的端点=控制器的请求映射+方法的请求映射。我提到的 GET 映射在 /。更改为

    .antMatchers(HttpMethod.GET, "/version/", "/story/", "/prompt/").permitAll()
                    .antMatchers(HttpMethod.POST, "/user/sign_in/").permitAll()
    

    事情正在发生。

    【讨论】:

      【解决方案2】:

      这对我有用:

       .and().authorizeRequests().antMatchers("/URL1/**", "/URL2/**").anonymous().anyRequest().authenticated();
      

      【讨论】:

        【解决方案3】:

        对我来说,它适用于

        .antMatchers(HttpMethod.GET, "/api/specific/**").permitAll()
        .antMatchers("/api/**").authenticated()
        

        请注意,在这种情况下,特定端点是在需要身份验证的通用端点之前使用 permitAll() 设置的。反过来就不行了。

        【讨论】:

          猜你喜欢
          • 2019-08-19
          • 2019-02-10
          • 2015-07-01
          • 2023-03-27
          • 2017-05-10
          • 1970-01-01
          • 2020-11-13
          • 2020-11-11
          • 2016-03-25
          相关资源
          最近更新 更多