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

-完-

相关推荐
taopi202435 分钟前
android java系统弹窗的基础模板
android·java·开发语言
松仔log1 小时前
Java多线程——对象的组合
java·开发语言·jvm
酷爱码1 小时前
springboot 动态配置定时任务
java·spring boot·后端
计算机-秋大田2 小时前
基于SpringBoot的美食烹饪互动平台的设计与实现(源码+SQL脚本+LW+部署讲解等)
vue.js·spring boot·后端·课程设计·美食
从未止步..2 小时前
Jenkins未在第一次登录后设置用户名,第二次登录不进去怎么办?
java·运维·jenkins
老马啸西风2 小时前
IM 即时通讯系统-42-基于netty实现的IM服务端,提供客户端jar包,可集成自己的登录系统
java
2501_903238652 小时前
Java 9模块开发:Eclipse实战指南
java·开发语言·eclipse·个人开发
test猿2 小时前
hive为什么建表,表存储什么
java
程序猿零零漆3 小时前
SpringCloud系列教程:微服务的未来(二十)Seata快速入门、部署TC服务、微服务集成Seata
java·spring·spring cloud·微服务
我的K84094 小时前
Spring Boot基本项目结构
java·spring boot·后端