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

    }
}

测试

结论

复制代码
最终可以发现我们可以自定义认证规则,让例如注册等不需要认证的请求直接放行,让其他请求进行认证操作后再进行放行
相关推荐
皙然12 分钟前
深入理解 Java HashMap:从底层原理、源码设计到面试考点全解析
java·开发语言·面试
元Y亨H17 分钟前
RuoYi-Cloud-Vue 架构全解析:微服务+前后端分离
java·微服务
子超兄18 分钟前
ThreadLocal相关问题
java
啊唯不困1 小时前
AI智能应用开发(Java)起点-终点 -1、java的前世今生andJava环境配置、jdk下载,以及Idea下载和基本应用
java·开发语言·intellij-idea
_muffinman1 小时前
Java学习笔记-第2章 运算和语句
java·笔记·学习
荒夜长歌1 小时前
传统java行业跳槽面试汇总(后续会更新)
java·面试·跳槽
旷世奇才李先生1 小时前
065智慧农业专家远程指导系统-springboot+vue
java·vue.js·spring boot
大迪deblog1 小时前
系统架构设计-软件架构风格
java·开发语言·架构·软件构建
盐水冰1 小时前
【烘焙坊项目】后端搭建(10) - 地址簿功能&用户下单&微信支付
java·数据库·后端
馨谙1 小时前
Kubernetes 核心技术之 Namespace:资源隔离与环境管理全解析
容器·kubernetes