簡體   English   中英

當 Spring SecurityContextHolder 在 getPrincipal 上返回 null 時,應該拋出哪個異常?

[英]Which exception should be thrown, when Spring SecurityContextHolder returns null on getPrincipal?

哪個異常最適合描述 RESTful 設計中缺少 Spring 安全主體,例如,當我從SecurityContextHolder.getContext().getAuthentication().getPrincipal()獲取主體時得到null時?

我有一個帶有自定義授權服務的項目,其中一部分需要有關已登錄的委托人以及他擁有哪些權限的信息。

一些(但不是全部)REST 端點也受 Spring 安全保護。

但是系統越來越大,可能會出現一個錯誤,未經授權的用戶將通過 Controller 層,並嘗試通過自定義授權服務訪問受保護的數據。

一方面,最適合的異常似乎是AccessDeniedException (Http 403),但另一方面,拋出 500 或 404 以“隱藏”所請求資源的存在可能是一種更安全的方法。

我想到了以下例外:

  • HttpStatus: 500 由org.springframework.security.access.AuthorizationServiceException引起
  • HttpStatus:403 org.springframework.security.access.AccessDeniedException
  • HttpStatus: 500 caused by java.lang.IllegalStateException
  • HttpStatus: 500 caused by java.lang.NullPointerException

我不相信哪種方法更好——禁止、隱藏或拋出內部服務器錯誤。

如果您使用的是 Spring 安全和自定義授權服務,您可能會遇到這樣的情況:

@Component
public class CustomAccessDeniedHandler extends AccessDeniedHandlerImpl {
    private final String HOME_PAGE = "/index.html";

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        if (auth != null) {

            if (auth instanceof AnonymousAuthenticationToken) {
                response.sendRedirect("/#/login");
                super.handle(request, response, e);
                return;
            }

            if (auth.getAuthorities().iterator().next().getAuthority().equals("ROLE_EMPLOYEE") || auth.getAuthorities().iterator().next().getAuthority().equals("ROLE_ADMIN") ) {
                 response.sendRedirect("/dashboard/Dashboard.xhtml");
                 super.handle(request, response, e);
                 return;
            }     
             response.sendRedirect("/#/dashboard/user");        
        }
        super.handle(request, response, e);
    }
}  

在您的情況下,在應用程序中,我寧願建議重定向到登錄屏幕 - 如上所示 - 並帶有類似Please log in的消息。

在 API 中,我會返回404 - Resource not found響應。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM