SpringSecurity自定義成功失敗處理器的示例代碼
1. 新建SpringBoot工程

2. 項目依賴
<dependencies>
<!-- security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- tomcat -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
3. 定義登錄成功處理器
- 新建一個類實現(xiàn)AuthenticationSuccessHandler
- 重寫onAuthenticationSuccess方法
package zw.springboot.controller;
import lombok.SneakyThrows;
import org.json.JSONObject;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @className LoginSuccessHandler
* @description 登錄成功處理器
* @author 周威
* @date 2020-09-03 13:50
**/
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler
{
@SneakyThrows
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException
{
// 設(shè)置response緩沖區(qū)字符集
response.setCharacterEncoding("UTF-8");
// 定義一個JSONObject對象
JSONObject object = new JSONObject();
// 填寫登錄成功響應信息
object.put("code", 1);
object.put("msg", "登錄成功");
// 設(shè)置響應頭
response.setContentType("application/json;charset=utf-8");
// 獲得打印輸出流
PrintWriter pw = response.getWriter();
// 向客戶端寫入一個字符串
pw.print(object.toString());
// 關(guān)閉流資源
pw.close();
}
}
4. 定義登錄失敗處理器新建一個類實現(xiàn)AuthenticationFailureHandler接口重寫onAuthenticationFailure方法
package zw.springboot.controller;
import lombok.SneakyThrows;
import org.json.JSONObject;
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;
import java.io.PrintWriter;
/**
* @className LoginErrorHandler
* @description 登錄失敗處理器
* @author 周威
* @date 2020-09-03 13:57
**/
@Component
public class LoginErrorHandler implements AuthenticationFailureHandler
{
@SneakyThrows
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException, ServletException
{
// 設(shè)置response緩沖區(qū)字符集
response.setCharacterEncoding("UTF-8");
// 定義一個JSONObject對象
JSONObject object = new JSONObject();
// 填寫登錄失敗響應信息
object.put("code", -1);
object.put("msg", "登錄失敗");
// 設(shè)置響應頭
response.setContentType("application/json;charset=utf-8");
// 獲得打印輸出流
PrintWriter pw = response.getWriter();
// 向客戶端寫入一個字符串
pw.print(object.toString());
// 關(guān)閉流資源
pw.close();
}
}
5. 安全認證配置類
package zw.springboot.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
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.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
/**
* @className SpringSecurityConfig
* @description 安全人認證配置類
* @author 周威
* @date 2020-09-03 13:42
**/
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter
{
@Autowired
private AuthenticationSuccessHandler loginSuccessHandler;
@Autowired
private AuthenticationFailureHandler loginErrorHandler;
// 定義用戶信息服務
@Bean
@Override
protected UserDetailsService userDetailsService()
{
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
// 模擬兩個用戶身份
manager.createUser(User.withUsername("admin").password(passwordEncoder().encode("123456")).authorities("p1").build());
manager.createUser(User.withUsername("user").password(passwordEncoder().encode("654321")).authorities("p2").build());
return manager;
}
// 定義密碼加密器
@Bean
public PasswordEncoder passwordEncoder()
{
return new BCryptPasswordEncoder();
}
// 定義攔截機制
@Override
protected void configure(HttpSecurity http) throws Exception
{
http
.authorizeRequests()
// 設(shè)置哪些請求需要認證
.antMatchers("/**").authenticated()
.and()
// 啟用表單登錄認證
.formLogin()
// 指定登錄成功處理器
.successHandler(loginSuccessHandler)
// 指定登錄失敗處理器
.failureHandler(loginErrorHandler);
}
}
6. 項目運行測試

7. 登錄成功測試

8. 登錄失敗測試

總結(jié)
到此這篇關(guān)于SpringSecurity自定義成功失敗處理器的示例代碼的文章就介紹到這了,更多相關(guān)SpringSecurity成功失敗處理器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springboot配置kafka批量消費,并發(fā)消費方式
文章介紹了如何在Spring Boot中配置Kafka進行批量消費,并發(fā)消費,需要注意的是,并發(fā)量必須小于等于分區(qū)數(shù),否則會導致線程空閑,文章還總結(jié)了創(chuàng)建Kafka分區(qū)的命令,并鼓勵讀者分享經(jīng)驗2024-12-12
Spring mvc整合tiles框架的簡單入門教程(maven)
這篇文章主要給大家介紹了關(guān)于Spring mvc整合tiles框架的簡單入門教程(maven),文中通過示例代碼介紹的非常詳細,對大家具有一定的參考學習價值,需要的朋友可以參考借鑒,下面來一起看看詳細的介紹吧。2017-12-12
Spring框架花式創(chuàng)建Bean的n種方法(小結(jié))
這篇文章主要介紹了Spring框架花式創(chuàng)建Bean的n種方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-03-03
IDEA 程序包不存在,找不到符號但是明明存在對應的jar包(問題分析及解決方案)
這篇文章主要介紹了IDEA 程序包不存在,找不到符號但是明明存在對應的jar包 的解決方案,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-08-08
淺談idea live template高級知識_進階(給方法,類,js方法添加注釋)
下面小編就為大家?guī)硪黄獪\談idea live template高級知識_進階(給方法,類,js方法添加注釋)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-06-06
SpringBoot如何通過devtools實現(xiàn)熱部署
這篇文章主要介紹了SpringBoot如何通過devtools實現(xiàn)熱部署,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-11-11

