日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

spring boot security之前后端分離配置

作者:不識君的荒漠 更新時間: 2023-07-04 編程語言

前言

spring boot security默認(rèn)配置有一個登錄頁面,當(dāng)采用前后端分離的場景下,需要解決兩個問題:

  1. 前端有自己的登錄頁面,不需要使用spring boot security默認(rèn)的登錄頁面
  2. 登錄相關(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的擴(kuò)展方法不只這一種,化繁為簡,盡量采用最簡單直白的方式。

認(rèn)證失敗自定義處理

當(dāng)請求認(rèn)證失敗的時候,可以返回一個401的狀態(tài)碼,這樣前端頁面可以根據(jù)響應(yīng)做相關(guān)處理,而不是出現(xiàn)默認(rèn)的登錄頁面或者登錄表單:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 在這里自定義配置
        http.authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .exceptionHandling()
                // 認(rèn)證失敗返回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 的基本認(rèn)證.
                .httpBasic();
    }

在這里插入圖片描述

登錄相關(guān)接口匿名訪問

登錄接口或者驗證碼需要匿名訪問,不應(yīng)該被攔截。
如下,提供獲取驗證碼和登錄的接口示例:

@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

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新