如何配置spring security 3.2以使用java配置使用dao身份验证和自定义身份验证过滤器

 手机用户2502926851 发布于 2023-01-30 11:17

我使用dao身份验证和自定义身份验证过滤器搜索了Spring安全示例,但是我发现,所有示例都使用xml文件配置,

我的问题是如何配置自定义过滤器,即UsernamePasswordAuthenticationFilter

我的基于xml的securityConfig文件如下所示:



            
         
            
          
    
    


    

    

    

    

      
        
    









      
     
                              
    
    




我想将配置转换为基于Java的配置 ..我试过这样做是不行的:

SecurityConfig类:

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder encoder;

    /*@Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth)throws Exception {
        logger.info("configureGlobal(AuthenticationManagerBuilder auth) invoked..");
        auth.userDetailsService(userDetailsService).passwordEncoder(encoder);       
    }*/

    @Override
    protected void configure(HttpSecurity http) throws Exception {  
        http.csrf().disable().authorizeRequests()
            .antMatchers("/resources/**","/assets/**","/files/**").permitAll()
            .antMatchers("/auth","/").permitAll()                           

                .anyRequest().authenticated() //every request requires the user to be authenticated
                .and()
            .formLogin() //form based authentication is supported
                .loginPage("/auth/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();

        http.exceptionHandling().accessDeniedPage("/auth/accessDenied");

        http.sessionManagement().sessionFixation().migrateSession()
            .sessionAuthenticationStrategy(concunSessContAuthStr());
    }

    @Bean(name="sessionRegistry")
    public SessionRegistryImpl sessionRegistryBean(){
        logger.info("sessionRegistryBean() invoked..");
        return new SessionRegistryImpl();
    }

    @Bean
    public UsernamePasswordAuthenticationFilter authFilter() throws Exception{
        logger.info("authFilter() invoked.."); 
        CustomUsernamePasswordAuthenticationFilter upaf = new CustomUsernamePasswordAuthenticationFilter();
        upaf.setAuthenticationManager(".."); //here, how to set AuthenticationManager ??
        upaf.setSessionAuthenticationStrategy(concunSessContAuthStr());
        return upaf;
    }


    @Bean
    public DaoAuthenticationProvider customAuthenticationManagerBean() {

        DaoAuthenticationProvider dap = new DaoAuthenticationProvider();
        dap.setUserDetailsService(userDetailsService);
        dap.setPasswordEncoder(encoder);
        return dap;
    }

    @Bean
    public ConcurrentSessionControlAuthenticationStrategy concunSessContAuthStr(){
        logger.info("concunSessContAuthStr() invoked.."); 
        ConcurrentSessionControlAuthenticationStrategy cscas= new ConcurrentSessionControlAuthenticationStrategy(sessionRegistryBean());
        cscas.setMaximumSessions(2);
        cscas.setExceptionIfMaximumExceeded(true);
        return cscas;
    }

}

任何建议如何配置?

谢谢!

1 个回答
  • 要使用替换UsernamePasswordAuthenticationFilter的自定义类,请执行以下操作:

    FormLoginConfigurer使用以下内容创建一个新类(原始版本org.springframework.security.config.annotation.web.configurers.FormLoginConfigurer不幸是最终版,无法扩展),请注意以下内容super(new CustomAuthenticationProcessingFilter(),null):

    package demo;
    
    import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
    import org.springframework.security.config.annotation.web.configurers.AbstractAuthenticationFilterConfigurer;
    import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
    import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter;
    import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
    import org.springframework.security.web.util.matcher.RequestMatcher;
    
    public class FormLoginConfigurer<H extends HttpSecurityBuilder<H>> extends AbstractAuthenticationFilterConfigurer<H,FormLoginConfigurer<H>,UsernamePasswordAuthenticationFilter> {
    
    public FormLoginConfigurer() {
        super(new CustomAuthenticationProcessingFilter(),null);
        usernameParameter("username");
        passwordParameter("password");
    }
    
    public FormLoginConfigurer<H> loginPage(String loginPage) {
        return super.loginPage(loginPage);
    }
    
    public FormLoginConfigurer<H> usernameParameter(String usernameParameter) {
        getAuthenticationFilter().setUsernameParameter(usernameParameter);
        return this;
    }
    
    public FormLoginConfigurer<H> passwordParameter(String passwordParameter) {
        getAuthenticationFilter().setPasswordParameter(passwordParameter);
        return this;
    }
    
    @Override
    public void init(H http) throws Exception {
        super.init(http);
        initDefaultLoginFilter(http);
    }
    
    @Override
    protected RequestMatcher createLoginProcessingUrlMatcher(
            String loginProcessingUrl) {
        return new AntPathRequestMatcher(loginProcessingUrl, "POST");
    }
    
    private String getUsernameParameter() {
        return getAuthenticationFilter().getUsernameParameter();
    }
    
    private String getPasswordParameter() {
        return getAuthenticationFilter().getPasswordParameter();
    }
    
    private void initDefaultLoginFilter(H http) {
        DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http.getSharedObject(DefaultLoginPageGeneratingFilter.class);
        if(loginPageGeneratingFilter != null && !isCustomLoginPage()) {
            loginPageGeneratingFilter.setFormLoginEnabled(true);
            loginPageGeneratingFilter.setUsernameParameter(getUsernameParameter());
            loginPageGeneratingFilter.setPasswordParameter(getPasswordParameter());
            loginPageGeneratingFilter.setLoginPageUrl(getLoginPage());
            loginPageGeneratingFilter.setFailureUrl(getFailureUrl());
            loginPageGeneratingFilter.setAuthenticationUrl(getLoginProcessingUrl());
        }
    }
    

    }

    formLogin()从您的configure(HttpSecurity)方法中删除调用并使用以下初始化:

     FormLoginConfigurer formLogin = new FormLoginConfigurer();
     http.apply(formLogin);
     formLogin.loginPage("/auth/login")
             .permitAll();
    

    身份验证管理器将自动提供给您的实例

    您可以SessionAuthenticationStrategy通过调用来自定义类中使用的http.sessionManagement(),或者您可以为新的逻辑添加逻辑,以便根据FormLoginConfigurer需要进行更新

    另一种选择是将CustomUsernamePasswordAuthenticationFilter过滤器注册为附加过滤器:

    configure(HttpSecurity http)方法调用中:

     http.addFilter(authFilter());
    

    确保手动配置过滤器的所有选项

    请注意,系统还会在您的后面添加UsernamePasswordAuthenticationFilter的另一个实例

    要添加自定义AuthenticationProvider:

    覆盖方法configure(AuthenticationManagerBuilder auth)并添加提供者:

     @Override
     protected void configure(AuthenticationManagerBuilder auth) throws Exception {
         auth.authenticationProvider(customAuthenticationManagerBean());
     }
    

    2023-01-30 11:18 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有