37 lines
1.5 KiB
Java
37 lines
1.5 KiB
Java
package com.baiyue.common.security;
|
|
|
|
import com.baiyue.common.core.api.ApiResponse;
|
|
import com.baiyue.common.core.api.ResultCode;
|
|
import com.baiyue.common.web.CorrelationContext;
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
import jakarta.servlet.http.HttpServletRequest;
|
|
import jakarta.servlet.http.HttpServletResponse;
|
|
import org.springframework.http.MediaType;
|
|
import org.springframework.security.core.AuthenticationException;
|
|
import org.springframework.security.web.AuthenticationEntryPoint;
|
|
|
|
import java.io.IOException;
|
|
import java.nio.charset.StandardCharsets;
|
|
|
|
/**
|
|
* 未认证请求处理器,以统一 JSON 结构返回 HTTP 401 错误。
|
|
*/
|
|
public class JsonAuthenticationEntryPoint implements AuthenticationEntryPoint {
|
|
private final ObjectMapper objectMapper;
|
|
|
|
public JsonAuthenticationEntryPoint(ObjectMapper objectMapper) {
|
|
this.objectMapper = objectMapper;
|
|
}
|
|
|
|
@Override
|
|
public void commence(HttpServletRequest request, HttpServletResponse response,
|
|
AuthenticationException authException) throws IOException {
|
|
ResultCode code = ResultCode.UNAUTHORIZED;
|
|
response.setStatus(code.httpStatus().value());
|
|
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
|
|
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
|
objectMapper.writeValue(response.getWriter(), ApiResponse.failure(code, code.message(),
|
|
CorrelationContext.requestId(request), CorrelationContext.traceId(request)));
|
|
}
|
|
}
|