2017-03-03 17 views
0

私はSuccessfulLoginHandlersetDefaultTargetUrl('...')があるアプリケーションを持っています。春 - 複数のURLを設定する最良の方法 - setDefaultTarget

今、ユーザーが別のビューを参照してログインできる1つのケースを実装する必要があります。これまでの私のやり方は:

@Service 
public class SuccessfulLoginHandler extends SimpleUrlAuthenticationSuccessHandler{ 

    UserService userService; 

    @Autowired 
    public SuccessfulLoginHandler(UserService userService){ 
     this.userService = userService; 
     setDefaultTargetUrl("/app"); 
    } 

    @Override 
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, 
     Authentication authentication) throws IOException, ServletException { 
     User user = AccessService.getUser(authentication); 
     if(this.userService.isFirstLogin(user)){ 
      setDefaultTargetUrl("/firstlogin"); 
     }else{ 
      setDefaultTargetUrl("/app"); 
     } 
     super.onAuthenticationSuccess(request, response, authentication); 
    } 

} 

私はこれが最善の方法であるかどうかは分かりません。正常に動作していますが、2人のユーザーが同時にログインする場合には問題になる可能性があります。

「リダイレクト」を実装する正しい方法は何でしょうか。

+1

解決方法は私によく見えます。また、2人のユーザーが同時にログインすると問題はありません。(唯一の共有リソースはuserserviceであり、スレッドセーフである必要があります) – fateddy

+0

あなたは正しいと思いますが、確かに私のコントローラにロジックを移しました。私はリダイレクトを行います。 – gon250

答えて

-1

ログインに成功すると、ユーザーをデフォルトのURLにリダイレクトできます。

あなたがSpring Securityを使用している場合は、単に成功したURLまたは失敗URLを設定できます。あなたがログイン成功後、いくつかのカスタムロジックを設定したい場合は、あなたがこのような何かを行うことができます

http 
    .authorizeRequests() 
     .anyRequest().authenticated() 
     .and() 
    .formLogin() 
     .loginPage("/login") 
     .failureUrl("/login?login_error=t") 
     .defaultSuccessUrl("/app") 
     .permitAll() 

public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { 

    String queryString = request.getQueryString(); 
    if(queryString == null) { 
     response.setStatus(200); 
    } else if(!queryString.contains("redirectUrl=")) { 
     response.sendRedirect("/"); 
    } else { 
     queryString = URLDecoder.decode(queryString.replace("url=", ""), "utf-8");    
     response.sendRedirect(queryString);    
    } 
} 

P.S.リダイレクトの場合、サーバーサイドリダイレクトを使用する場合は、response.sendRedirectではなくrequest.getRequestDispathcerを使用できます。

EDIT:userServiceは読み取り専用サービスであり、競合状態の問題を引き起こしてはならないため、同時ログインで問題は発生しません。

関連する問題