1. 程式人生 > >Spring security筆記4/4: 自定義成功和失敗

Spring security筆記4/4: 自定義成功和失敗

自定義成功和失敗

還是在之前示例的基礎上,將認證成功跳轉頁面,修改為認證成功返回資料

實現步驟

1. 複製上一示例的原始碼

重新命名包名 case3 為 case4

重新命名 Case3Application.java 為 Case4Application.java

2. 在 WebSecurityConfig 中配置登入頁

在 config(HttpSecurity http) 方法中對 formLogin 選項進行配置。需要包含以下設定:

  • 建立 SuccessHandler 實現 AuthenticationSuccessHandler 介面,並實現 onAuthenticationSuccess 方法,自定義返回內容;
  • 建立 FailureHandler 實現 AuthenticationFailureHandler 介面,並實現 onAuthenticationFailure 方法,自定義返回內容;
  • 在 formLogin 配置項上增加 successHandler 和 failureHandler 配置

相關程式碼如下:

package net.txt100.learn.springsecurity.base.case4.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
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;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

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

/**
 * Title: WebSecurityConfig
 * Package: net.txt100.learn.springsecurity.base.case2.config
 * Creation date: 2019-08-11
 * Description:
 *
 * @author <a href="[email protected]">Tonglei</a>
 * @since 1.0
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        // 配置密碼的保護策略,spring security 預設使用 bcrypt 加密演算法。
        // 此處只要顯式宣告 BCryptPasswordEncoder Bean 即可
        return new BCryptPasswordEncoder();
    }

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

        AuthenticationSuccessHandler successHandler = new AuthenticationSuccessHandler() {
            @Override
            public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                response.setContentType("application/json;charset=UTF-8");
                JSON.writeJSONString(response.getOutputStream(), authentication);
            }
        };

        AuthenticationFailureHandler failureHandler = new AuthenticationFailureHandler() {
            @Override
            public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
                response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                response.setContentType("application/json;charset=UTF-8");
                JSON.writeJSONString(response.getOutputStream(), exception);
            }
        };

        http
            .csrf().disable() // 關閉 CSRF 保護功能,否則不支援 Post 請求
            .authorizeRequests() // 針對 HttpServletRequest 進行安全配置
                .antMatchers("/login.html").permitAll() // login.html 頁面無需登入即可訪問
                .anyRequest().authenticated() // 對所有 Request 均需安全認證
            .and().formLogin()
                .successHandler(successHandler)
                .failureHandler(failureHandler)
            .and().httpBasic(); // 定義如何驗證使用者,此項代表彈出瀏覽器認證視窗
    }
}

3. 登入測試

  1. 嘗試認證失敗,此時返回如下 (不同瀏覽器環境效果可能不同)

  1. 嘗試認證成功,此時返回如下

總結

通過修改 formLogin 配置,可以讓認證中心提供更豐