繁体   English   中英

如何使用Java配置表示Spring Security“自定义过滤器”?

[英]How to represent the Spring Security “custom-filter” using Java configuration?

Spring Security <custom-filter>标记的等效Java配置是什么?

<http>
  <custom-filter position="FORM_LOGIN_FILTER" ref="myFilter"/>
</http>

我试过了

http.addFilter( new MyUsernamePasswordAuthenticationFilter() )

类扩展默认过滤器,但它始终使用formLogin默认值。

我的过滤器:

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication; 
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter{

    // proof of concept of how the http.addFilter() works

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }

        System.out.println("running my own version of UsernmePasswordFilter ... ");

        String username = obtainUsername(request);
        String password = obtainPassword(request);

        if (username == null) {
            username = "";
        }

        if (password == null) {
            password = "";
        }

        username = username.trim();

        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);

        // Allow subclasses to set the "details" property
        setDetails(request, authRequest);

        return this.getAuthenticationManager().authenticate(authRequest);
    }
}

相关配置文件:

@Configuration
@EnableWebMvcSecurity  // annotate class configuring AuthenticationManagerBuilder
@ComponentScan("com.kayjed")
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

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

      http
        .authorizeRequests()
            .antMatchers("/resources/**","/signup").permitAll()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/login")
            .permitAll()
            .and()
        .logout()
            .permitAll();

      http.addFilter(new MyUsernamePasswordAuthenticationFilter());
    }

    ...
}

在调试器中运行MVC应用程序始终显示登录尝试从默认UsernamePasswordAuthenticationFilter身份验证,而不是使用MyUsernamePasswordAuthenticationFilter类。

无论如何,我不是想让某人调试代码; 相反,我希望看到一个使用Java配置的好例子,它在XML方法中执行等效的custom-filter元素。 文档有点简洁。

您可能需要记住以下几个问题:

  1. 您的过滤器需要在标准UsernamePasswordAuthenticationFilter 之前添加

     http.addFilterBefore(customUsernamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class) 
  2. 如果您扩展UsernamePasswordAuthenticationFilter,除非您设置RequestMatcher否则您的过滤器将立即返回,而不会执行任何操作

     myAuthFilter.setRequiresAuthenticationRequestMatcher( new AntPathRequestMatcher("/login","POST")); 
  3. 您在http.formLogin().x().y().z()执行的所有配置都应用于标准UsernamePasswordAuthenticationFilter而不是您构建的自定义过滤器。 您需要自己手动配置它。 我的auth过滤器初始化如下所示:

     @Bean public MyAuthenticationFilter authenticationFilter() { MyAuthenticationFilter authFilter = new MyAuthenticationFilter(); authFilter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/login","POST")); authFilter.setAuthenticationManager(authenticationManager); authFilter.setAuthenticationSuccessHandler(new MySuccessHandler("/app")); authFilter.setAuthenticationFailureHandler(new MyFailureHandler("/login?error=1")); authFilter.setUsernameParameter("username"); authFilter.setPasswordParameter("password"); return authFilter; } 

我在这段代码中没有发现任何问题。 我认为,你的配置很好。 问题出在别的地方。我有类似的代码,

package com.programsji.config;

import java.util.ArrayList;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import com.programsji.security.CustomAuthenticationProvider;
import com.programsji.security.CustomSuccessHandler;
import com.programsji.security.CustomUsernamePasswordAuthenticationFilter;

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

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/js/**", "/css/**", "/theme/**").and()
                .debug(true);
    }

    @Bean
    public CustomUsernamePasswordAuthenticationFilter customUsernamePasswordAuthenticationFilter()
            throws Exception {
        CustomUsernamePasswordAuthenticationFilter customUsernamePasswordAuthenticationFilter = new CustomUsernamePasswordAuthenticationFilter();
        customUsernamePasswordAuthenticationFilter
                .setAuthenticationManager(authenticationManagerBean());
        customUsernamePasswordAuthenticationFilter
                .setAuthenticationSuccessHandler(customSuccessHandler());
        return customUsernamePasswordAuthenticationFilter;
    }

    @Bean
    public CustomSuccessHandler customSuccessHandler() {
        CustomSuccessHandler customSuccessHandler = new CustomSuccessHandler();
        return customSuccessHandler;
    }

    @Bean
    public CustomAuthenticationProvider customAuthenticationProvider() {
        CustomAuthenticationProvider customAuthenticationProvider = new CustomAuthenticationProvider();
        return customAuthenticationProvider;
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        List<AuthenticationProvider> authenticationProviderList = new ArrayList<AuthenticationProvider>();
        authenticationProviderList.add(customAuthenticationProvider());
        AuthenticationManager authenticationManager = new ProviderManager(
                authenticationProviderList);
        return authenticationManager;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/reportspage").hasRole("REPORT")
                .antMatchers("/rawdatapage").hasRole("RAWDATA").anyRequest()
                .hasRole("USER").and().formLogin().loginPage("/login")
                .failureUrl("/login?error")
                .loginProcessingUrl("/j_spring_security_check")
                .passwordParameter("j_password")
                .usernameParameter("j_username").defaultSuccessUrl("/")
                .permitAll().and().httpBasic().and().logout()
                .logoutSuccessUrl("/login?logout").and().csrf().disable()
                .addFilter(customUsernamePasswordAuthenticationFilter());
    }

}

它在我的应用程序上正常工作。 你可以从网址下载整个项目: https//github.com/programsji/rohit/tree/master/UsernamePasswordAuthenticationFilter

尝试将@Component添加到MyUsernamePasswordAuthenticationFilter类。

此注释使该类被视为自动检测的候选者,请参阅: @Component


为了这:

<custom-filter position="FORM_LOGIN_FILTER" ref="myFilter"/>

你可以添加这个:

.addFilter[Before|After](authenticationTokenProcessingFilter, UsernamePasswordAuthenticationFilter.class)

请参阅: 标准过滤器别名和排序

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM