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

    }
}

测试

结论

复制代码
最终可以发现我们可以自定义认证规则,让例如注册等不需要认证的请求直接放行,让其他请求进行认证操作后再进行放行
相关推荐
特立独行的猫A3 分钟前
13MB 单文件、一条命令变服务:把仓颉写的 cjh 内嵌进你的应用,当它的 AI 大脑
java·后端·python
Brookty10 分钟前
Java博客项目实战|工程环境与构建:工程目录、PowerShell命令调用与JDK/IDEA/Maven工作机制
java·项目实战
养军博客34 分钟前
Spring Boot 3.x + Spring Security 6.x 整合 JWT 实战:jjwt 与 java-jwt 两种工具库详解
java·spring boot·springsecurity
TeamDev43 分钟前
使用 JxBrowser 在桌面应用中集成 Spring
java·前端·后端·spring·混合应用·jxbrowser·浏览器控件
J.YA1 小时前
String字符串[面试题]
java·开发语言
金銀銅鐵10 小时前
为什么枚举类中可以定义抽象方法
java·后端·ai编程
文丑颜不良啊12 小时前
LeetCode1941~1960题目解析
java·leetcode
txxzjmzlh12 小时前
SpringBoot 统⼀功能处理
java·spring boot·后端
nice_lcj52014 小时前
Java Lambda 表达式入门:怎么写、怎么用、常用方法有哪些
java·开发语言·后端·面试
码农小河6614 小时前
基于SSM+JSP+MySQL的在线医疗服务系统的设计与实现
java·开发语言·mysql