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();
    }
}
相关推荐
左左右右左右摇晃2 小时前
Java并发——synchronized锁
java·开发语言
sxlishaobin2 小时前
Java I/O 模型详解:BIO、NIO、AIO
java·开发语言·nio
彭于晏Yan2 小时前
Spring AI(二):入门使用
java·spring boot·spring·ai
有一个好名字3 小时前
vibe codeing 开发流程
java
兑生3 小时前
【灵神题单·贪心】3745. 三元素表达式的最大值 | 排序贪心 | Java
java·开发语言
polaris06303 小时前
Windows操作系统部署Tomcat详细讲解
java·windows·tomcat
卓怡学长3 小时前
m280本科生导师指导平台
java·数据库·spring·tomcat·maven·intellij-idea
一直都在5723 小时前
Java死锁
java·开发语言
我真会写代码4 小时前
深度解析并发编程锁升级:从偏向锁到重量级锁,底层原理+面试考点全拆解
java·并发编程·
Meepo_haha4 小时前
创建Spring Initializr项目
java·后端·spring