2017-07-12 54 views
0

一些背景Spring Security认证是空的错误页面重定向后

当我试图建立与用户的信息和角色访问我遇到了一些问题,从验证检索404错误页面上的信息一个导航栏(Spring Security)处理拦截器。

@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/")); 
    } 
} 

当我访问某些网页像本地主机/不存在页/它会被重定向到本地主机/错误/ 404/和处理在以下控制器上:

@Controller 
@RequestMapping(value = "/errors") 
public class ErrorController { 

    @RequestMapping(value = "/{error}/") 
    public String errorRedirect(@PathVariable String error) { 
     return "errors/error" + error; 
    } 
} 

回答

0

如果您想获得认证的客户,请尝试@AuthenticationPrincipal注释。

+0

你到底在哪里?在ErrorController,ServerPropertiesConfig或AuthenticationHandlerInterceptor? –

相关问题