溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Spring security中怎么自定義成功和失敗

發(fā)布時(shí)間:2021-06-18 15:21:55 來(lái)源:億速云 閱讀:164 作者:Leah 欄目:大數(shù)據(jù)

本篇文章為大家展示了Spring security中怎么自定義成功和失敗,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。

實(shí)現(xiàn)步驟

1. 復(fù)制上一示例的源碼

重命名包名 case3 為 case4

重命名 Case3Application.java 為 Case4Application.java

2. 在 WebSecurityConfig 中配置登錄頁(yè)

在 config(HttpSecurity http) 方法中對(duì) formLogin 選項(xiàng)進(jìn)行配置。需要包含以下設(shè)置:

  • 創(chuàng)建 SuccessHandler 實(shí)現(xiàn) AuthenticationSuccessHandler 接口,并實(shí)現(xiàn) onAuthenticationSuccess 方法,自定義返回內(nèi)容;

  • 創(chuàng)建 FailureHandler 實(shí)現(xiàn) AuthenticationFailureHandler 接口,并實(shí)現(xiàn) onAuthenticationFailure 方法,自定義返回內(nèi)容;

  • 在 formLogin 配置項(xiàng)上增加 successHandler 和 failureHandler 配置

相關(guān)代碼如下:

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="zgjt_tongl@thunis.com">Tonglei</a>
 * @since 1.0
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        // 配置密碼的保護(hù)策略,spring security 默認(rèn)使用 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() // 關(guān)閉 CSRF 保護(hù)功能,否則不支持 Post 請(qǐng)求
            .authorizeRequests() // 針對(duì) HttpServletRequest 進(jìn)行安全配置
                .antMatchers("/login.html").permitAll() // login.html 頁(yè)面無(wú)需登錄即可訪問(wèn)
                .anyRequest().authenticated() // 對(duì)所有 Request 均需安全認(rèn)證
            .and().formLogin()
                .successHandler(successHandler)
                .failureHandler(failureHandler)
            .and().httpBasic(); // 定義如何驗(yàn)證用戶,此項(xiàng)代表彈出瀏覽器認(rèn)證窗口
    }
}

上述內(nèi)容就是Spring security中怎么自定義成功和失敗,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI