简体   繁体   English

Spring Boot 2 Interceptor在每个请求上都解析“ / login”

[英]Spring Boot 2 Interceptor resolves `/login' on every request

Inside Spring boot security I'm trying to redirect server side the login page within Spring boot automatically to an overview page if I detect that the user is already logged in. The login screen should only show when the user is logged out. 在Spring Boot安全性内部,如果我检测到用户已登录,则尝试将服务器端在Spring Boot中的登录页面自动重定向到概述页面。仅在用户注销时才显示登录屏幕。

@Configuration
public class MvcConfig implements WebMvcConfigurer
{

   @Override
   public void addInterceptors( InterceptorRegistry registry )
   {
      registry.addInterceptor( new LoginInterceptor() ).addPathPatterns( "/login" );
   }

Inside LoginInterceptor I have: 在LoginInterceptor内部,我有:

   @Override
   public boolean preHandle( HttpServletRequest request, HttpServletResponse response, Object handler ) throws Exception
   {

      Authentication auth = SecurityContextHolder.getContext().getAuthentication();
      String url = request.getRequestURL().toString();
      System.out.println(url);
      if( auth.isAuthenticated() )
      {
         response.sendRedirect( "/my/overview" );
         return false;
      }

      return true;
   }

However, even if I am logged in, the debugger seems to think that I'm still on the /login route. 但是,即使我已登录,调试器似乎也认为我仍在/ login路由上。 Does spring boot route every request through /login for checking authentication? spring boot是否通过/login路由每个请求以检查身份验证? How do I achieve my aim of not resolving the login page unless the user is logged out? 我如何实现除非用户注销否则不解决登录页面的目标?

Actually what was happening here was 'anonymousUser' was being returned for isAuthenticated, and thus the authenticated method wasn't working. 实际上,这里发生的是为isAuthenticated返回了“ anonymousUser”,因此authenticated方法无法正常工作。 The redirect for unauthorised accounts kicked in making me think that everything was going through login route when it was actually just the security doing its thing. 对于未经授权的帐户的重定向使我觉得一切都在通过登录路径进行,而实际上这只是安全性在起作用。 checking for principle null was the way to go instead. 检查原理是否为null是替代方法。

 if( auth.isAuthenticated() && principal != null )
 {
      response.sendRedirect( OVERVIEW_PAGE );
      return false;
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM