Spring boot 3 (3.1.5) Spring Security 设置一

项目依赖中添加:

Groovy 复制代码
testImplementation 'org.springframework.security:spring-security-test'

创建Security设置文件:

SecutiryConfig.java

java 复制代码
import com.example.sino.utils.JWTFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@EnableWebSecurity
@Configuration
public class SecurityConfig {

    @Autowired
    private JWTFilter jwtFilter;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(
                authorize -> authorize
                        .requestMatchers("/api/welcome").permitAll() // 公开访问
                        .requestMatchers("/api/admin").hasAuthority("ADMIN") // ADMIN权限
                        .anyRequest().authenticated() // 其它必须登录才能访问
        );

        

        // Spring Security 6 中默认是关闭登录表单的,这里如果添加以下代码则是开启登录表单。
        // 开启登录表单
        // http.formLogin(Customizer.withDefaults());
        
        // 禁用csrf
        http.csrf(AbstractHttpConfigurer::disable);

        // 验证token
        http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }





}

测试

创建两个路由 /api/welcome 和 /api/admin。分别访问。

/api/welcome 直接就能看到内容, /api/admin 则返回401

java 复制代码
import com.example.sino.domain.JsonResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class WelcomeController {

    @RequestMapping("welcome")
    public JsonResult index() {
        return JsonResult.success("Welcome!");
    }


    @RequestMapping("admin")
    public JsonResult admin() {
        return JsonResult.success("Hi admin.");
    }
}

附录:

JsonResult代码

java 复制代码
import java.util.HashMap;

public class JsonResult extends HashMap<String, Object> {
    // 业务状态码
    public static final String CODE_TAG = "code";
    // 消息
    public static final String MSG_TAG = "msg";
    // 数据
    public static final String DATA_TAG = "data";


    public JsonResult() {
    }

    public JsonResult(int code, String msg) {
        super.put(CODE_TAG, code);
        super.put(MSG_TAG, msg);
    }

    public JsonResult(int code, String msg, Object data) {
        super.put(CODE_TAG, code);
        super.put(MSG_TAG, msg);
        if (data != null) {
            super.put(DATA_TAG, data);
        }
    }



    /**
     * 返回成功消息
     *
     * @return 成功消息
     */
    public static JsonResult success() {
        return JsonResult.success("操作成功");
    }

    /**
     * 返回成功数据
     *
     * @return 成功消息
     */
    public static JsonResult success(Object data) {
        return JsonResult.success("操作成功", data);
    }

    /**
     * 返回成功消息
     *
     * @param msg 返回内容
     * @return 成功消息
     */
    public static JsonResult success(String msg) {
        return JsonResult.success(msg, null);
    }

    /**
     * 返回成功消息
     *
     * @param msg 返回内容
     * @param data 数据对象
     * @return 成功消息
     */
    public static JsonResult success(String msg, Object data) {
        return new JsonResult(200, msg, data);
    }



    /**
     * 返回错误消息
     *
     * @return 错误消息
     */
    public static JsonResult error() {
        return JsonResult.error("操作失败");
    }

    /**
     * 返回错误消息
     *
     * @param msg 返回内容
     * @return 错误消息
     */
    public static JsonResult error(String msg) {
        return JsonResult.error(msg, null);
    }

    /**
     * 返回错误消息
     *
     * @param msg  返回内容
     * @param data 数据对象
     * @return 错误消息
     */
    public static JsonResult error(String msg, Object data) {
        return new JsonResult(500, msg, data);
    }


    
    /**
     * 方便链式调用
     *
     * @param key   键
     * @param value 值
     * @return 数据对象
     */
    @Override
    public JsonResult put(String key, Object value) {
        super.put(key, value);
        return this;
    }
}

JWTFilter.java代码见下期,还没整明白。

-完-

相关推荐
懒虫虫~9 分钟前
基于SpringBoot解决RabbitMQ消息丢失问题
spring boot·rabbitmq
大春儿的试验田35 分钟前
Parameter ‘XXX‘ not found. Available parameters are [list, param1]
java
java干货1 小时前
深度解析:Spring Boot 配置加载顺序、优先级与 bootstrap 上下文
前端·spring boot·bootstrap
程序员JerrySUN1 小时前
[特殊字符] 深入理解 Linux 内核进程管理:架构、核心函数与调度机制
java·linux·架构
2302_809798321 小时前
【JavaWeb】Docker项目部署
java·运维·后端·青少年编程·docker·容器
网安INF2 小时前
CVE-2020-17519源码分析与漏洞复现(Flink 任意文件读取)
java·web安全·网络安全·flink·漏洞
一叶知秋哈2 小时前
Java应用Flink CDC监听MySQL数据变动内容输出到控制台
java·mysql·flink
jackson凌2 小时前
【Java学习笔记】SringBuffer类(重点)
java·笔记·学习
sclibingqing2 小时前
SpringBoot项目接口集中测试方法及实现
java·spring boot·后端
程序员JerrySUN2 小时前
全面理解 Linux 内核性能问题:分类、实战与调优策略
java·linux·运维·服务器·单片机