私の春のプロジェクトでは、クライアントのアクティブセッション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
が正しく再度読み込まれます。 (パスマッチングはもちろんありません)
なぜですか?