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代码见下期,还没整明白。

-完-

相关推荐
Wyc724093 分钟前
Maven
java·数据库·maven
程序猿小D6 分钟前
[附源码+数据库+毕业论文]基于Spring+MyBatis+MySQL+Maven+jsp实现的电影小说网站管理系统,推荐!
java·数据库·mysql·spring·毕业设计·ssm框架·电影小说网站
CodeWithMe1 小时前
【Note】《深入理解Linux内核》 Chapter 15 :深入理解 Linux 页缓存
linux·spring·缓存
木头没有瓜1 小时前
idea离线安装插件
java·ide·intellij-idea
一勺菠萝丶1 小时前
Spring Boot + MyBatis/MyBatis Plus:XML中循环处理List参数的终极指南
xml·spring boot·mybatis
llwszx2 小时前
Spring中DelayQueue深度解析:从原理到实战(附结构图解析)
java·后端·spring·delayqueue·延迟任务
述雾学java2 小时前
Spring Cloud Feign 整合 Sentinel 实现服务降级与熔断保护
java·spring cloud·sentinel
保持学习ing2 小时前
苍穹外卖day3--公共字段填充+新增菜品
java·阿里云·实战·springboot·前后端·外卖项目·阿里云文件存储
77qqqiqi2 小时前
正则表达式
java·后端·正则表达式
厦门德仔2 小时前
【WPF】WPF(样式)
android·java·wpf