SpringBoot整合SpringSecurity

📑前言

本文主要是【SpringSecurity】——SpringBoot整合SpringSecurity的文章,如果有什么需要改进的地方还请大佬指出⛺️

🎬作者简介:大家好,我是听风与他🥇
☁️博客首页:CSDN主页听风与他
🌄每日一句:狠狠沉淀,顶峰相见


在这里插入图片描述

1.导入依赖pom.xml

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>

2.编写返回信息的记录类RestBean

package com.it.myprojectbackend.entity;


import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;

public record RestBean<T>(int code, T data, String message) {
	public static <T> RestBean<T> success(T data){
		return new RestBean<>(200,data,"请求成功");
	}

	public static <T> RestBean<T> success(){
		return success(null);
	}

	public String asJsonString(){
		return 	JSONObject.toJSONString(this, JSONWriter.Feature.WriteNulls);
	}

	public static <T> RestBean<T> failure(int code,String message){
		return new RestBean<>(code,null,message);
	}

	public static void main(String[] args) {
		System.out.println(RestBean.success("hello").asJsonString());
	}
}

3.编写SecurityConfiguration配置类

package com.it.myprojectbackend.config;

import com.it.myprojectbackend.entity.RestBean;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
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.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import java.io.IOException;

@Configuration
public class SecurityConfiguration {

	@Bean
	public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
		return httpSecurity
				//拦截
				.authorizeHttpRequests(conf -> conf
						.requestMatchers("/api/auth/**").permitAll()
						.anyRequest().authenticated())
				//登录
				.formLogin(conf -> conf
						.loginProcessingUrl("/api/auth/login")
						.successHandler(this::onAuthenticationSuccess)
						.failureHandler(this::onAuthenticationFailure))
				//登出
				.logout(conf -> conf
						.logoutUrl("/api/auth/logout")
						.logoutSuccessHandler(this::onLogoutSuccess)
				)
				.csrf(AbstractHttpConfigurer::disable)
				//session的状态改为无状态,无状态管理
				.sessionManagement(conf -> conf.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
		.build();
	}

	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
		response.setContentType("application/json;charset=utf-8");
		response.getWriter().write(RestBean.success().asJsonString());
	}

	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
		response.setContentType("application/json;charset=utf-8");
		response.getWriter().write(RestBean.failure(401, exception.getMessage()).asJsonString());
	}

	public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

	}
}

4.测试

成功

在这里插入图片描述

失败

在这里插入图片描述

📑文章末尾

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

听风与他

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值