RestAuthenticationEntryPoint.java
1.5 KB
package com.bs.web.security;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
private static final Logger log = LoggerFactory.getLogger(RestAuthenticationEntryPoint.class);
private final ObjectMapper mapper = new ObjectMapper();
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
log.warn("Unauthenticated access: method={}, path={}, msg={}", request.getMethod(), request.getRequestURI(), authException.getMessage());
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
Map<String, Object> body = new HashMap<>();
body.put("code", 401);
body.put("msg", "未登录或令牌无效");
body.put("path", request.getRequestURI());
response.getWriter().write(mapper.writeValueAsString(body));
}
}