欢迎来到徐庆高(Tea)的个人博客网站
磨难很爱我,一度将我连根拔起。从惊慌失措到心力交瘁,我孤身一人,但并不孤独无依。依赖那些依赖我的人,信任那些信任我的人,帮助那些给予我帮助的人。如果我愿意,可以分裂成无数面镜子,让他们看见我,就像看见自己。察言观色和模仿学习是我的领域。像每个深受创伤的人那样,最终,我学会了随遇而安。
当前位置: 日志文章 > 详细内容

springboot security之前后端分离配置方式

2025年03月31日 Java
前言spring boot security默认配置有一个登录页面,当采用前后端分离的场景下需要解决两个问题:前端有自己的登录页面,不需要使用spring boot security默认的登录页面登录

前言

spring boot security默认配置有一个登录页面,当采用前后端分离的场景下

需要解决两个问题:

  1. 前端有自己的登录页面,不需要使用spring boot security默认的登录页面
  2. 登录相关接口允许匿名访问

因此需要自定义相关实现。

自定义配置

自定义配置的核心实现如下:

@component
public class websecurityconfigurer extends websecurityconfigureradapter {

    @override
    protected void configure(httpsecurity http) throws exception {
        // 在这里自定义配置
    }
}

如上示例代码:

关键是重写这个方法,spring boot security的扩展方法不只这一种,化繁为简,尽量采用最简单直白的方式。

认证失败自定义处理

当请求认证失败的时候,可以返回一个401的状态码,这样前端页面可以根据响应做相关处理,而不是出现默认的登录页面或者登录表单:

    @override
    protected void configure(httpsecurity http) throws exception {
        // 在这里自定义配置
        http.authorizerequests()
                .anyrequest()
                .authenticated()
                .and()
                .exceptionhandling()
                // 认证失败返回401状态码,前端页面可以根据401状态码跳转到登录页面
                .authenticationentrypoint((request, response, authexception) ->
                        response.senderror(httpstatus.unauthorized.value(), httpstatus.unauthorized.getreasonphrase()))
                .and().cors()
                // csrf是否决定禁用,请自行考量
                .and().csrf().disable()
//                .antmatcher("/**")
                // 采用http 的基本认证.
                .httpbasic();
    }

登录相关接口匿名访问

登录接口或者验证码需要匿名访问,不应该被拦截。

如下,提供获取验证码和登录的接口示例:

@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()
                // 登录相关接口都允许访问
                .antmatchers("/login/**").permitall()
                // 还有其它接口就这样继续写
                .antmatchers("/other/**").permitall()
                .anyrequest()
                .authenticated()
				... 省略下面的
    }

前置文章

spring boot security快速使用示例

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。