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

    }
}

测试

结论

复制代码
最终可以发现我们可以自定义认证规则,让例如注册等不需要认证的请求直接放行,让其他请求进行认证操作后再进行放行
相关推荐
桦说编程2 小时前
从 ForkJoinPool 的 Compensate 看并发框架的线程补偿思想
java·后端·源码阅读
蝎子莱莱爱打怪4 小时前
GitLab CI/CD + Docker Registry + K8s 部署完整实战指南
后端·docker·kubernetes
躺平大鹅4 小时前
Java面向对象入门(类与对象,新手秒懂)
java
初次攀爬者5 小时前
RocketMQ在Spring Boot上的基础使用
java·spring boot·rocketmq
花花无缺5 小时前
搞懂@Autowired 与@Resuorce
java·spring boot·后端
Derek_Smart6 小时前
从一次 OOM 事故说起:打造生产级的 JVM 健康检查组件
java·jvm·spring boot
NE_STOP7 小时前
MyBatis-mybatis入门与增删改查
java
孟陬10 小时前
国外技术周刊 #1:Paul Graham 重新分享最受欢迎的文章《创作者的品味》、本周被划线最多 YouTube《如何在 19 分钟内学会 AI》、为何我不
java·前端·后端
想用offer打牌10 小时前
一站式了解四种限流算法
java·后端·go