📑前言
本文主要是【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 {
}
}