網(wǎng)站首頁 編程語言 正文
前言
spring boot security默認配置有一個登錄頁面,當采用前后端分離的場景下,需要解決兩個問題:
- 前端有自己的登錄頁面,不需要使用spring boot security默認的登錄頁面
- 登錄相關(guān)接口允許匿名訪問
因此需要自定義相關(guān)實現(xiàn)。
自定義配置
自定義配置的核心實現(xiàn)如下:
@Component
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// 在這里自定義配置
}
}
如上示例代碼,關(guān)鍵是重寫這個方法,spring boot security的擴展方法不只這一種,化繁為簡,盡量采用最簡單直白的方式。
認證失敗自定義處理
當請求認證失敗的時候,可以返回一個401的狀態(tài)碼,這樣前端頁面可以根據(jù)響應做相關(guān)處理,而不是出現(xiàn)默認的登錄頁面或者登錄表單:
@Override
protected void configure(HttpSecurity http) throws Exception {
// 在這里自定義配置
http.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.exceptionHandling()
// 認證失敗返回401狀態(tài)碼,前端頁面可以根據(jù)401狀態(tài)碼跳轉(zhuǎn)到登錄頁面
.authenticationEntryPoint((request, response, authException) ->
response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase()))
.and().cors()
// csrf是否決定禁用,請自行考量
.and().csrf().disable()
// .antMatcher("/**")
// 采用http 的基本認證.
.httpBasic();
}
登錄相關(guān)接口匿名訪問
登錄接口或者驗證碼需要匿名訪問,不應該被攔截。
如下,提供獲取驗證碼和登錄的接口示例:
@RequestMapping("/login")
@RestController
public class LoginController {
@PostMapping()
public Object login() {
return "login success";
}
@GetMapping("/captcha")
public Object captcha() {
return "1234";
}
}
配置允許訪問這部分接口:
@Override
protected void configure(HttpSecurity http) throws Exception {
// 在這里自定義配置
http.authorizeRequests()
// 登錄相關(guān)接口都允許訪問
.antMatchers("/login/**").permitAll()
// 還有其它接口就這樣繼續(xù)寫
.antMatchers("/other/**").permitAll()
.anyRequest()
.authenticated()
... 省略下面的
}
前置文章
spring boot security快速使用示例
原文鏈接:https://blog.csdn.net/x763795151/article/details/131445388
- 上一篇:沒有了
- 下一篇:沒有了
相關(guān)推薦
- 2023-04-27 antd?upload上傳如何獲取文件寬高_React
- 2022-08-15 apollo配置中心的client端分析
- 2022-04-12 npm ERR! missing script: dev
- 2022-06-17 C語言深入講解函數(shù)參數(shù)的使用_C 語言
- 2022-06-26 python中class類與方法的用法實例詳解_python
- 2023-06-17 C#?輸出參數(shù)out問題_C#教程
- 2022-09-14 iOS實現(xiàn)簡單長截圖_IOS
- 2022-06-12 詳解Go語言中的數(shù)據(jù)類型及類型轉(zhuǎn)換_Golang
- 欄目分類
-
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支