fix: return structured JSON on auth failure for login error message
CI/CD Deploy (Admin) / 构建后端镜像并部署 (push) Successful in 21s

This commit is contained in:
张家训
2026-09-03 18:35:25 +08:00
parent 030916e6aa
commit 59e796c65f
@@ -1,6 +1,10 @@
package com.freedom.admin.config;
import com.alibaba.fastjson.JSON;
import com.freedom.admin.common.Result;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
@@ -21,15 +25,23 @@ public class MyAuthenticationFailureHandler implements AuthenticationFailureHand
public void onAuthenticationFailure(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException e) throws IOException {
//修改编码格式
request.setCharacterEncoding("utf-8");
response.setContentType("application/json");
// 修改编码格式
response.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=utf-8");
if (e instanceof BadCredentialsException){
response.getWriter().write("用户名或密码错误");
}else {
response.getWriter().write("登录失败!");
String message;
if (e instanceof BadCredentialsException) {
message = "用户名或密码错误";
} else if (e instanceof LockedException) {
message = "账号已被锁定,请联系管理员";
} else if (e instanceof DisabledException) {
message = "账号已被禁用,请联系管理员";
} else {
message = "登录失败,请稍后重试";
}
// 返回结构化 JSON(HTTP 200 + 业务码),前端依据 message 提示用户;
// code 415 为前端模板预留的凭据类错误码
Result result = Result.error().code(415).message(message);
response.getWriter().write(JSON.toJSONString(result));
}
}