哪个异常最适合描述RESTful设计中缺少Spring Security Principal,例如,当我从null
获取Principal时又得到SecurityContextHolder.getContext().getAuthentication().getPrincipal()
的情况?
我有一个带有自定义授权服务的项目,其中一部分需要有关已登录的委托人以及他拥有哪些权限的信息。
一些(但不是全部)REST端点也受到Spring Security的保护。
但是,系统变得越来越大,并且可能会发生错误,未经授权的用户将通过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 Security和自定义授权服务,则可能会有以下内容:
@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
响应。关于java - 当Spring SecurityContextHolder在getPrincipal上返回null时,应该引发哪个异常?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58497616/