Spring boot 3 (3.1.5) Spring Security 设置一

项目依赖中添加:

testImplementation 'org.springframework.security:spring-security-test'

创建Security设置文件:

SecutiryConfig.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

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代码


import java.util.HashMap;

public class JsonResult extends HashMap {
    // 业务状态码
    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代码见下期,还没整明白。

-完-

你可能感兴趣的:(Spring,Boot,spring,boot,spring,java)