SpringSecurity6从入门到实战之SpringSecurity6自定义认证规则

SpringSecurity6从入门到实战之SpringSecurity6自定义认证规则

Spring Security 中默认所有的 http 请求都需要先认证通过后,才能访问。那么, 如何指定不需要认证就可以直接访问的资源呢?比如 用户的登录页面和注册页面,都是不需要认证就必须能被直接访问的。这就需要设置自定义的URL认证规则

SpringSecurity5.x自定义认证与6.x

java 复制代码
# 在 SpringSecurity5.x中( 了解,已被废弃 )
    // 自定义配置类 继承 WebSecurityConfigurerAdapter 类覆盖 configure() 方法
    @Configuration
    public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
       @Override
       protected void configure(HttpSecurity http) throws Exception {
           http.authorizeHttpRequests()
                .mvcMatchers("/hello").permitAll()
                .anyRequest().authenticated()
                .and().formLogin();
       }
    }
# 在 SpringSecurity6.x 中
    // 自定义配置类 使用注解 @EnableWebSecurity 配置 SpringSecurity

开发示例

创建一个新的controller

/test

java 复制代码
package com.example.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String hello() {
        System.out.println("/hello");
        return "hello...";
    }

    @RequestMapping("/test")
    public String test() {
        System.out.println("/test");
        return "test...";
    }
}

方便与/hello对比进行测试

根据SpringSecurity6.x自定义认证规则配置

新建MyWeSecurityConfig自定义配置类

java 复制代码
package com.example.config;

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 MyWeSecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        //放行hello和test
        http.authorizeHttpRequests().requestMatchers("/hello", "test").permitAll()
            //所有请求都需要进行认证
                .anyRequest().authenticated()
            //进行表单登录验证
            .and().formLogin();
        return http.build();

    }
}

测试

结论

复制代码
最终可以发现我们可以自定义认证规则,让例如注册等不需要认证的请求直接放行,让其他请求进行认证操作后再进行放行
相关推荐
shehuiyuelaiyuehao2 分钟前
7类和对象
java·开发语言
岚天start8 分钟前
Containerd 运行时的 K8S 集群离线导入镜像的方案
容器·containerd·容器运行时
凤凰战士芭比Q8 分钟前
Jenkins(Pipeline job)
java·servlet·jenkins
喵了几个咪14 分钟前
开箱即用的 GoWind Admin|风行,企业级前后端一体中后台框架:kratos-bootstrap 入门教程(类比 Spring Boot)
spring boot·后端·微服务·golang·bootstrap
代码不停18 分钟前
BFS解决拓扑排序和FloodFill问题
java·算法·宽度优先
孤岛悬城23 分钟前
44 Docker:安装与容器管理
docker·容器·云计算
Chengbei1124 分钟前
CVE-2025-24813 Tomcat 最新 RCE 分析复现
java·安全·web安全·网络安全·tomcat·系统安全·网络攻击模型
AAA简单玩转程序设计29 分钟前
救命!Java 进阶居然还在考这些“小儿科”?
java·前端
总是学不会.34 分钟前
【JUC编程】多线程学习大纲
java·后端·开发
MediaTea37 分钟前
思考与练习(第十章 文件与数据格式化)
java·linux·服务器·前端·javascript