Spring Security自定義認證失敗處理器響應


自定義認證失敗處理器

package com.mengxuegu.security.authentication;

import com.mengxuegu.base.result.MengxueguResult;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component("customAuthenticationFailureHandler")
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        AuthenticationException e) throws IOException, ServletException {
        MengxueguResult result = MengxueguResult.build(
                HttpStatus.UNAUTHORIZED.value(), e.getMessage());
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.getWriter().write(result.toJsonString());
    }
}

配置認證失敗處理器

package com.mengxuegu.security.config;

import com.mengxuegu.security.properties.AuthenticationProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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 org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;


/**
 * alt+/ 導包
 * ctrl+o 覆蓋
 * @Auther: 夢學谷 www.mengxuegu.com
 */
@EnableWebSecurity // 開啟springsecurity過濾鏈 filter
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {


    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private AuthenticationProperties authenticationProperties;

    @Bean
    public PasswordEncoder passwordEncoder(){
        // 明文+隨機鹽值-》加密存儲
        return new BCryptPasswordEncoder();
    }

    @Autowired
    UserDetailsService customUserDetailsService;

    @Autowired
    private AuthenticationSuccessHandler customAuthenticationSuccessHandler;

    @Autowired
    private AuthenticationFailureHandler customAuthenticationFailureHandler;

    /**
     * 認證管理器:
     * 1. 認證信息(用戶名,密碼)
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        String password = passwordEncoder().encode("123456");
//        logger.info("加密之后存儲的密碼:"+password);
//        auth.inMemoryAuthentication().withUser("root").password(password).authorities("ADMIN");
        auth.userDetailsService(customUserDetailsService);
    }

    /**
     * 資源權限配置:
     * 1. 被攔截的資源
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        System.out.println("用戶認證");
//       http.httpBasic() // 采用 httpBasic認證方式
        http.formLogin() // 表單登錄方式
                .loginPage(authenticationProperties.getLoginPage())   //配置登錄頁面
                .loginProcessingUrl(authenticationProperties.getLoginProcessingUrl())  //登錄表單提交處理url,默認是/login
                .usernameParameter(authenticationProperties.getUsernameParameter())
                .passwordParameter(authenticationProperties.getPasswordParameter())
                .successHandler(customAuthenticationSuccessHandler) // 認證成功處理器
                .failureHandler(customAuthenticationFailureHandler) // 認證失敗處理器
            .and()
            .authorizeRequests() // 認證請求
            .antMatchers(authenticationProperties.getLoginPage()).permitAll()
            .anyRequest().authenticated() //所有訪問該應用的http請求都要通過身份認證才可以訪問
        ; // 注意不要少了分號
    }

    /**
     * 一般針對靜態資源放行
     * @param web
     */
    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers(authenticationProperties.getStaticPaths());
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM