【问题标题】:Spring Security anyRequest.authenticated behaviorSpring Security anyRequest.authenticated 行为
【发布时间】:2021-11-05 23:32:16
【问题描述】:

我正在尝试实现一个简单的 Spring 安全项目,但我面临一个问题,即 http.authorizeRequests().anyRequest().authenticated(); 的行为无法理解。我对这种方法的期望是阻止所有传入的请求,直到用户通过身份验证,但在我的情况下,所有请求都通过并且没有发生拦截。当我取消注释包含 hasAnyAuthority 的行时,阻止请求通过的正常行为发生了。

以下是我的安全配置

@Override
    protected void configure(HttpSecurity http) throws Exception {
        CustomAuthFilter customAuthFilter = new CustomAuthFilter(authenticationManagerBean());
       //override behavior of url for our api

        customAuthFilter.setFilterProcessesUrl("/api/login");
        http.csrf().disable();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);


        http.authorizeRequests().antMatchers("/api/login/**").permitAll();
        http.authorizeRequests().antMatchers("/register/**").permitAll();
        /////http.authorizeRequests().antMatchers(GET,"/api/users/").hasAnyAuthority("ROLE_USER");
        //////http.authorizeRequests().antMatchers(POST,"/api/user/save/**").hasAnyAuthority("ROLE_ADMIN");

        http.authorizeRequests().anyRequest().authenticated();
        http.addFilter(customAuthFilter);
        http.addFilterBefore(new CustomAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

【问题讨论】:

  • 您能分享一下您的CustomAuthFilter 实现吗?另外,分享您请求的端点。

标签: java spring spring-security


【解决方案1】:

我已经解决了这个问题,这只是对经过身份验证的方法如何工作的误解。

所以首先 Spring 安全检查用户是否经过身份验证,然后检查此端点是否需要任何类型的授权。如果经过身份验证且不存在授权,则用户将被重定向到端点。现在对我来说很有意义。

谢谢。

【讨论】:

    猜你喜欢
    • 2021-08-02
    • 2019-10-10
    • 1970-01-01
    • 2012-01-16
    • 2015-09-07
    • 1970-01-01
    • 2015-12-17
    • 2016-09-01
    • 2016-11-13
    相关资源
    最近更新 更多