【问题标题】:Spring Security: authentication page permitAll seems to be ignoredSpring Security:身份验证页面 permitAll 似乎被忽略了
【发布时间】:2017-09-16 06:56:12
【问题描述】:

我正在使用 Spring Security 编写应用程序。 我已经实现了我的自定义 UserDetails、UserDetailsS​​ervice、AccessDecisionVoter 和 WebSecurityConfigurerAdapter。 我想允许未经授权的用户访问 /authenthication/login 页面进行登录,但对页面的所有其他访问都需要由自定义 AccessDecisionVoter 处理。
我的自定义 WebSecurityConfigurerAdapter 类如下所示:

@Configuration
@EnableWebSecurity
@ComponentScan(value = "security")
public class Configuration extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsServiceImpl userDetailsServiceImpl;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/authentication/login**")
                .permitAll()
                .and()
            .authorizeRequests()
                .anyRequest()
                .authenticated()
                .accessDecisionManager(accessDecisionManager())
        ;
    }


    @Bean
    public AccessDecisionManager accessDecisionManager() {
        List<AccessDecisionVoter<? extends Object>> decisionVoters =
                Arrays.asList(new AccessDecisionVoterImpl());
        return new UnanimousBased(decisionVoters);
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) {
        try {
            auth.userDetailsService(userDetailsServiceImpl);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Bean
    public UserDetailsServiceImpl userDetailsService() {
        return userDetailsServiceImpl;
    }

}

我在我的数据库中定义了几个角色。我的自定义 AccessDecisionVoter 中的 vote 方法检索已登录用户的权限,并根据该权限和 URL + httpMethod 授予或拒绝访问权限。

问题:
但是,当我使用用户名和密码向 /authentication/login 发送 POST 时,我的代码在自定义 AccessDecisionVoter 中给了我一个 NullPointerException:用户名(通过 authentication.getPrincipal(); 检索返回anonymousUser,这会导致稍后在代码中出现 NullPointer。但我不明白为什么 vote 方法会被调用,因为配置文件告诉 Spring 允许所有访问 /authentication/login

【问题讨论】:

    标签: java spring security authentication authorization


    【解决方案1】:

    我相信您设置它的方式, permitAll 只是允许所有请求(即使是未经身份验证的请求),但它不会禁用该请求的安全链,它仍会尝试通过它们进行处理全部。如果你只是想绕过所有的安全,我通常使用的方法是覆盖 webSecurity 配置方法并在那里添加异常情况,如下所示:

    @Override
    public void configure(WebSecurity webSecurity) throws Exception
    {
        webSecurity
            .ignoring()
            .antMatchers("/authentication/login**");
    }   
    

    【讨论】:

      猜你喜欢
      • 2014-03-11
      • 2018-08-12
      • 2016-10-13
      • 2013-08-23
      • 2021-10-28
      • 2016-09-30
      • 2012-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多