[英]Spring Security Authentication is null after Error page redirect
一些背景
當我嘗試使用用戶信息和角色訪問權限來構建導航欄時,在從處理程序攔截器上的Authentication(Spring Security)的404錯誤頁面上檢索這些信息時,我遇到了一些問題。
@Component
public class AuthenticationHandlerInterceptor implements HandlerInterceptor {
@Autowired
private IAuthenticationFacade authenticationFacade;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
if (modelAndView != null) {
Authentication authentication = authenticationFacade.getAuthentication(); // <- Unexpected Null
if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken)) {
modelAndView.getModel().put("user",
new UserModel(
authentication.getName(),
AuthorityUtils.authorityListToSet(authentication.getAuthorities())
)
); //put
} //fi
}//fi
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {}
}
IAuthenticationFacade已按照baeldung的建議實施。
問題
在我與某些用戶進行身份驗證之后,所有頁面請求都將通過postHandle傳遞,並且有可能獲取當前用戶數據。 除非頁面由於某些404而被重定向。
下一行返回null。
Authentication authentication = authenticationFacade.getAuthentication();
錯誤重定向
@Configuration
public class ServerPropertiesConfig extends ServerProperties {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
super.customize(container);
container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/errors/404/"));
}
}
當我訪問諸如localhost / non-existing-page /之類的頁面時 ,它將被重定向到localhost / errors / 404 /並在以下控制器處進行處理:
@Controller
@RequestMapping(value = "/errors")
public class ErrorController {
@RequestMapping(value = "/{error}/")
public String errorRedirect(@PathVariable String error) {
return "errors/error" + error;
}
}
如果您想獲得經過身份驗證的客戶,請嘗試使用@AuthenticationPrincipal
批注。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.