fix: 修复token过期返回403

This commit is contained in:
ah--desktop
2025-09-25 22:36:10 +08:00
parent 570e8986cd
commit 2ddff44068
69 changed files with 398 additions and 335 deletions
@@ -10,6 +10,11 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.core.AuthenticationException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import top.xyquan.ecomdmbbackend.common.filter.JwtAuthenticationFilter;
import top.xyquan.ecomdmbbackend.utils.JwtUtils;
@@ -43,8 +48,23 @@ public class SecurityConfig {
"/swagger-ui/**", "/swagger-ui.html")
.permitAll()
.anyRequest().authenticated())
.exceptionHandling(exceptions -> exceptions
.authenticationEntryPoint(new CustomAuthenticationEntryPoint()))
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
/**
* 自定义认证入口点,返回401状态码
*/
private static class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write("{\"code\":401,\"message\":\"Token无效或已过期,请重新登录\",\"data\":null}");
}
}
}