Spring Boot + Spring Security

一、Spring Security 是 Spring Boot 自动识别

1、只要引入了 Spring Security 依赖,Spring Boot 就会自动启用它

复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

不需要写一行配置代码,Spring Security 就会生效。

Spring Boot 启动时就会:

✔ 自动创建一整套 Security Filter

✔ 自动保护所有接口

✔ 自动生成 /login 登录页(跳转到Spring Boot的默认 formLogin登录页面,这个路径并不是自己配置的路劲)

✔ 自动要求所有请求必须登录

2、自动配置默认做了什么

行为 默认值
所有接口 必须认证
登录方式 表单登录
登录地址 /login
登出地址 /logout
用户 自动生成一个
密码 启动日志打印

二、前后端分离的项目应该怎么做?

1、为什么前后端分离时 不适合

前后端分离时,正确行为是:

情况 正确返回
未登录 401 JSON
已登录 正常数据

默认 formLogin 会:

情况 实际行为
未登录 302 跳 /login
前端 拿到 HTML
Security 仍认为你没登录

➡️ 永远无法建立登录态 尤其是前端已经写了login的界面 永远也不会跳转到前端的登录界面

2、前后端路线

显式关闭 formLogin,返回 401

你必须写一个 SecurityConfig(这是关键一步):

复制代码
package com.hj.mapserver.config;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                // 前后端分离必须关闭表单登录和HTTP基本认证
                .formLogin(formLogin -> formLogin.disable())
                .httpBasic(httpBasic -> httpBasic.disable())

                // 未登录直接返回 401,不跳页面
                .exceptionHandling(exceptionHandling ->
                        exceptionHandling.authenticationEntryPoint((req, resp, e) -> {
                            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                        })
                )

                // 接口权限配置
                .authorizeHttpRequests(authorizeHttpRequests ->
                        authorizeHttpRequests
                                .requestMatchers("/login", "/check/**", "/query/system/user").permitAll()
                                .anyRequest().authenticated()
                )

                // 前后端分离关闭CSRF
                .csrf(csrf -> csrf.disable());

        return http.build();
    }
}
相关推荐
豆瓣鸡10 小时前
算法日记 - Day3
java·开发语言·算法
萧瑟余晖10 小时前
Java深入解析篇九之NIO详解
java·网络·nio
The Chosen One98511 小时前
高进度算法模板速记(待完善)
java·前端·算法
极光代码工作室13 小时前
基于SpringBoot的课程预约系统
java·springboot·web开发·后端开发
Leighteen13 小时前
`try-finally` 里的 `return`:为什么 `finally` 会悄悄改掉返回值、吞掉异常
java·开发语言
名字还没想好☜14 小时前
Go 的 time.After 在 select 循环里内存泄漏:定时器堆积原理与 timer.Reset 正确姿势
java·数据库·golang·go·goroutine
圆山猫14 小时前
[Virtualization](三):RISC-V H-extension 与 Guest 执行模式
android·java·risc-v
caishenzhibiao14 小时前
期货先行者主图 同花顺期货通指标
java·c语言·c#
史呆芬15 小时前
分布式事务实战:微服务跨服务数据一致性解决方案
java·后端·spring cloud
IT界的老黄牛15 小时前
限流命中后该怎么办:直接丢、阻塞等待、延迟重投三种姿势的取舍
java·rocketmq·redisson·令牌桶·削峰·分布式限流