SpringSecurity custom UsernamePasswordAuthenticationFilter

UsernamePasswordAuthenticationFilter介绍

UsernamePasswordAuthenticationFilter is AbstractAuthenticationProcessingFilter for a username and password for authentication while a customized filter. Its role is added when calling http.formLogin (), the default login request pattern is "/ login", and for the POST request. When we log in, that is matched to loginProcessingUrl, this filter will be commissioned to verify the authentication manager authenticationManager login.

Custom UsernamePasswordAuthenticationFilter

Here I need is to realize the front UsernamePasswordAuthenticationFilter pass over the RSA private key to decrypt the password by custom, and because the login address is not "/ login", so inherited AbstractAuthenticationProcessingFilter, if the default login address, you can re-direct successor UsernamePasswordAuthenticationFilter write attemptAuthentication method can be.

public class MyUsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "username";
    public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password";
    private String usernameParameter = SPRING_SECURITY_FORM_USERNAME_KEY;
    private String passwordParameter = SPRING_SECURITY_FORM_PASSWORD_KEY;
    private boolean postOnly = true;
    private String privateKey = "xxxxxxxxxxxxxxxxxxx";
    
    public MyUsernamePasswordAuthenticationFilter() {
        super(new AntPathRequestMatcher("/oauth/token", "POST"));
    }

    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {
        if (postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        String username = obtainUsername(request);
        String password = obtainPassword(request);
        try {
            password = RSAUtil.decrypt(password, privateKey);
        } catch (Exception e) {
            e.printStackTrace();
        }

        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 super.getAuthenticationManager().authenticate(authRequest);
    }

    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
        super.setAuthenticationManager(authenticationManager);
    }
    
    protected String obtainPassword(HttpServletRequest request) {
        return request.getParameter(passwordParameter).replaceAll(" ", "+");
    }

    protected String obtainUsername(HttpServletRequest request) {
        return request.getParameter(usernameParameter);
    }

    protected void setDetails(HttpServletRequest request,
            UsernamePasswordAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }

    public void setUsernameParameter(String usernameParameter) {
        Assert.hasText(usernameParameter, "Username parameter must not be empty or null");
        this.usernameParameter = usernameParameter;
    }

    public void setPasswordParameter(String passwordParameter) {
        Assert.hasText(passwordParameter, "Password parameter must not be empty or null");
        this.passwordParameter = passwordParameter;
    }
    
    public void setPostOnly(boolean postOnly) {
        this.postOnly = postOnly;
    }

    public final String getUsernameParameter() {
        return usernameParameter;
    }

    public final String getPasswordParameter() {
        return passwordParameter;
    }

}

MyUsernamePasswordAuthenticationFilter added to the custom filter chain Filter Chain

Use http.addFilterAt (myAuthenticationFilter (), UsernamePasswordAuthenticationFilter.class) SpringSecurity arranged in the class on the custom filter UsernamePasswordAuthenticationFilter position and to set the authentication success and failure processing method, and an authentication manager AuthenticationManager

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Autowired
    private AuthenticationSuccessHandler appLoginInSuccessHandler;
    
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        AuthenticationManager manager = super.authenticationManagerBean();
        return manager;
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated()
                .and().httpBasic().and()
                .cors().disable().headers().frameOptions().sameOrigin();// 解决iframe无法访问
        http.addFilterAt(myAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
MyUsernamePasswordAuthenticationFilter myAuthenticationFilter() throws Exception {
        MyUsernamePasswordAuthenticationFilter filter = new MyUsernamePasswordAuthenticationFilter();
        filter.setAuthenticationManager(authenticationManagerBean());
        filter.setAuthenticationSuccessHandler(appLoginInSuccessHandler);
        filter.setAuthenticationFailureHandler(new AuthenticationFailureHandler() {
            @Override
            public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(JSON.toJSONString(Respon.failed("登录失败!")));
            }
        });
        return filter;
    }
}

Custom UsernamePasswordAuthenticationFilter use

In addition to the above example, is also commonly used to modify the form log becomes Json format, the login authentication codes, etc., to be noted that the local address of the default login is UsernamePasswordAuthenticationFilter

 

Guess you like

Origin www.cnblogs.com/dang-/p/11535940.html