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();

    }
}

测试

结论

复制代码
最终可以发现我们可以自定义认证规则,让例如注册等不需要认证的请求直接放行,让其他请求进行认证操作后再进行放行
相关推荐
Wpa.wk几秒前
Docker容器 - 了解Docker基础命令(容器+镜像命令)
运维·经验分享·测试工具·docker·容器
Filotimo_1 分钟前
JWT的概念
java·开发语言·python
min1811234562 分钟前
软件升级全流程步骤详解
android·java·服务器
黎雁·泠崖4 分钟前
Java字符串系列总结篇|核心知识点速记手册
java·开发语言
biyezuopinvip10 分钟前
基于Spring Boot的社区互助平台设计与实现(毕业论文)
java·spring boot·vue·毕业设计·论文·毕业论文·社区互助平台设计与实现
Coder_Boy_17 分钟前
基于SpringAI的在线考试系统-试卷管理与考试管理模块联合回归测试文档
人工智能·spring boot·架构·领域驱动
J_liaty17 分钟前
Redis公共方法详解
spring boot·redis·后端
JNU freshman21 分钟前
从 Ceph 16(Pacific)到 Ceph 18(Reef):cephadm 的伸缩性演进与 cephadm agent 到底“成熟”了吗?
java·大数据·ceph
nbsaas-boot27 分钟前
为什么 ScopedValue 是 SaaS 的分水岭
java
小北方城市网28 分钟前
生产级 Spring Boot + MyBatis 核心配置模板
java·spring boot·redis·后端·spring·性能优化·mybatis