lxmsb/study-project-backend/src/main/java/com/example/config/SecurityConfiguration.java

54 lines
2.3 KiB
Java

package com.example.config;
import com.alibaba.fastjson2.JSONObject;
import com.example.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.configuration.EnableWebSecurity;
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 java.io.IOException;
@Configuration
@EnableWebSecurity
public class SecurityConfiguration {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginProcessingUrl("/api/auth/login")//登录页面
.successHandler(this::onAuthenticationSuccess)//登录成功返回
.failureHandler(this::onAuthenticationFailure)//登录失败返回
.and()
.logout()
.logoutUrl("api/auth/logout")
.and()
.csrf()
.disable()
//无权限返回
.exceptionHandling()
.authenticationEntryPoint(this::onAuthenticationFailure)
.and()
.build();
}
public void onAuthenticationSuccess (HttpServletRequest request, HttpServletResponse response, Authentication auth) throws IOException {
response.setCharacterEncoding("UTF-8");
response.getWriter().write(JSONObject.toJSONString(RestBean.success("登录成功!")));
}
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
response.setCharacterEncoding("UTF-8");
response.getWriter().write(JSONObject.toJSONString(RestBean.failure(401, exception.getMessage())));
}
}