Class JsonAuthenticationEntryPoint

java.lang.Object
io.leandev.appfuse.security.auth.JsonAuthenticationEntryPoint
All Implemented Interfaces:
org.springframework.security.web.AuthenticationEntryPoint

public class JsonAuthenticationEntryPoint extends Object implements org.springframework.security.web.AuthenticationEntryPoint

認證入口點,回傳 RFC 7807 格式的 JSON 錯誤回應

當認證失敗時,根據異常類型回傳對應的錯誤訊息。

回應範例:

{
  "type": "urn:appfuse:error:bad-credentials",
  "title": "Bad Credentials",
  "status": 401,
  "detail": "Invalid username or password",
  "instance": "/auth/login"
}

使用範例:

@Bean
public JsonAuthenticationEntryPoint jsonAuthenticationEntryPoint(ObjectMapper objectMapper) {
    JsonAuthenticationEntryPoint entryPoint = new JsonAuthenticationEntryPoint(objectMapper);

    // 可選:自訂訊息
    Map<Class<? extends AuthenticationException>, String> customMessages = new HashMap<>();
    customMessages.put(DisabledException.class, "Your account has been disabled");
    entryPoint.setCustomMessages(customMessages);

    return entryPoint;
}
  • Constructor Details

    • JsonAuthenticationEntryPoint

      public JsonAuthenticationEntryPoint(tools.jackson.databind.ObjectMapper objectMapper)
  • Method Details

    • setCustomMessages

      public void setCustomMessages(Map<Class<? extends org.springframework.security.core.AuthenticationException>, String> customMessages)
      設定自訂錯誤訊息
      Parameters:
      customMessages - 異常類別到錯誤訊息的對應表
    • commence

      public void commence(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response, org.springframework.security.core.AuthenticationException authException) throws IOException
      Specified by:
      commence in interface org.springframework.security.web.AuthenticationEntryPoint
      Throws:
      IOException