当前位置: 首页 > news >正文

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

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

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

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

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

开发示例

创建一个新的controller

/test

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自定义配置类

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

测试

image.png

image.png

结论

最终可以发现我们可以自定义认证规则,让例如注册等不需要认证的请求直接放行,让其他请求进行认证操作后再进行放行
http://www.lryc.cn/news/374202.html

相关文章:

  • Java IO:byte[]、char[]、String三种对象的转换
  • Elasticsearch:简化数据流的数据生命周期管理
  • Verilog综合出来的图
  • KT-H6测距模块标品,测距范围1500m,demo报价1000RMB,批量报价500RMB
  • C数据结构:排序
  • 【Python】在 Pandas 中使用 AdaBoost 进行分类
  • 持续总结中!2024年面试必问 20 道并发编程面试题(九)
  • Linux:线程池
  • 集成学习方法:Bagging与Boosting的应用与优势
  • JEnv-for-Windows 2 java版本工具的安装使用踩坑
  • linux中: IDEA 由于JVM 设置内存过小,导致打开项目闪退问题
  • d3.js获取流程图不同的节点
  • MFC socket编程-服务端和客户端流程
  • 22.1 正则表达式-定义正则表达式、正则语法
  • 网络数据包抓取与分析工具wireshark的安及使用
  • Docker镜像技术剖析
  • log4j漏洞学习
  • 架构设计 - WEB项目的基础序列化配置
  • java(JVM)
  • 【网络安全】【深度学习】【入侵检测】SDN模拟网络入侵攻击并检测,实时检测,深度学习【二】
  • 飞腾银河麒麟V10安装Todesk
  • JWT令牌、过滤器Filter、拦截器Interceptor
  • iText7画发票PDF——小tips
  • 跟着刘二大人学pytorch(第---10---节课之卷积神经网络)
  • transformer实战
  • 【Starrocks docker-compose部署】
  • Nginx 精解:正则表达式、location 匹配与 rewrite 重写
  • 代码随想录算法训练营Day37|56.合并区间、738.单调递增的数字、968.监控二叉树
  • Web前端开发12章:深入探索与实战解析
  • 八股操作系统和计算机网络