2017-11-28 14 views
0

私の春のプロジェクトでは、クライアントのアクティブセッションCookieのセキュリティコンテキストのユーザー詳細を返すエンドポイントを作成したいと考えています。セキュリティチェーンフィルタ内にSecurityContextが設定されていません

一つの方法は、

@RequestMapping(value = "/session", method = GET) 
public AuthenticatedUserDto getCurrentSession(HttpServletResponse response) { 
    if (SecurityContextHolder.getContext().getAuthentication().getPrincipal() != null && SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof User) { 
     return AuthenticatedUserBuilder.build(SecurityContextHolder.getContext().getAuthentication()); 
    } 
    throw new BadCredentialsException("unkown session"); 
} 

コントローラ内の特定のメソッドの実装になります。このアプローチで私を気がいくつかあります:

  • 私はそれがないかどうかを判断するために醜いifを必要とします匿名認証

  • 私はすべての情報を持っているので、この問題を文脈の中で深く扱っています。セッションクッキーが解決されるとすぐに。

、ちょうどAnonymousAuthenticationFilter前にフィルタを追加する必要がありますので、私の他のアプローチは、特定のURL( "/セッション)を合わせるためのセキュリティ・チェーン・フィルタを使用しており、そこにタスクを処理します。

public class SessionObjectResponder extends GenericFilterBean { 

    @Override 
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { 
     Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); 
     ...//do create my response 
     .. 
    } 
} 

。私はセッションクッキーを照合可能なセキュリティコンテキストを持っているでしょう保証はだから私は構成され、このように私のWebセキュリティ:奇妙

httpSecurity.antMatcher("/session").addFilterBefore(new SessionObjectResponder(),AnonymousAuthenticationFilter.class); 

SecurityContextHolder有効なセッションCookieが渡されてもnull認証が含まれます。 私はまた、SecurityContextPersistenceFilterの中にセキュリティコンテキストが設定されていないことがわかります。

このフィルタのhttpSecurity設定を削除し、フィルタクラスに@Componentを追加すると、SecurityContextが正しく再度読み込まれます。 (パスマッチングはもちろんありません)

なぜですか?

答えて

0

あなたはこのようなAuthenticationまたはPrincipalを求めることができます:

@RequestMapping(value = "/session", method = GET) 
public AuthenticatedUserDto getCurrentSession(Authentication auth) { 
    if (auth == null || !auth.isAuthenticated()) 
     throw new BadCredentialsException("unkown session"); 
    return AuthenticatedUserBuilder.build(auth); 
} 
0

あなたが@Componentまたは@Serviceまたは@Controllerを使用する場合...それは春がされて管理さになります。彼らのライフサイクルはスプリングコンテナによって管理されています。したがって、コンテキストはコンテナで作成されたインスタンスで使用できます。

しかし

httpSecurity.antMatcher("/session").addFilterBefore(new SessionObjectResponder(),AnonymousAuthenticationFilter.class); 

のあなたのケースでは、新しい演算子でインスタンスを作成しています。コンテナによって作成されるものではありません。したがって、このインスタンスはコンテナスコープの外にあります。したがって、実行時にそのインスタンスでコンテキストを使用することはできません。

関連する問題