私はSecurityWebFilterChainのJWT認証の内部を実行するためにWebFilterを追加しています。私は私のAPIハンドラメソッド(例えば、LoginControllerで情報というJWTとアクセスから情報を抽出できるようにする必要がありますように、我々は、私たちのAPIエンドポイントの多くが必要とされているJWT内の非認証関連の多くの情報を符号化します。 javaの)。これを達成するための最良のパターンとは何ですか?
ここでWebFilter認証を示す私のSecurityWebFilterChainは以下のとおりです。
@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
return http
.authorizeExchange()
.pathMatchers("/login", "/")
.authenticated()
.and()
.addFilterAt(basicAuthenticationFilter(), SecurityWebFiltersOrder.HTTP_BASIC)
.authorizeExchange()
.pathMatchers("/adm")
.authenticated()
.and()
.addFilterAt(basicAuthenticationFilter(), SecurityWebFiltersOrder.HTTP_BASIC)
.authorizeExchange()
.pathMatchers("/api/**")
.access(authorizationManager)
.and()
.addFilterAt(bearerAuthenticationFilter(), SecurityWebFiltersOrder.AUTHENTICATION)
.build();
}
私はLoginController.javaで、クレームにアクセスしたいのはここです:
@RestController()
@RequestMapping(value = "/login")
public class LoginController {
private final UserMongoRepository repository;
@Autowired
public LoginController(UserMongoRepository repository) {
this.repository = repository;
}
@PostMapping("")
public Mono<User> login(@RequestBody User post,
@RequestParam String user_id,
@RequestParam String username) {
//Need to access information from JWT claims here
return this.repository.findById(user_id);
}
}
私は、カスタマイズされた作成しAuthentication
たオブジェクトを、その内部に必要な情報を格納します。
ユーザ関連データ、その内部に格納するためにPrincipal
.FOR非ユーザ関連データ、のような音がDetails
店に良い場所です。
多くのビルトインAuthenticationProvider
作成するUserDetails
にして店をPrincipal
。ことを意味し、あなただけのcustomsied作成を検討することができUserDetails
ますが、それらが内蔵され、それを使用している場合AuthenticationProvider
。
ですから、認証ロジックを実装する方法に応じて、あなたは関連をカスタマイズする必要があるAuthenticationProvider
か、Filter
目的がアクセスしているなどHttpServletRequest
、HTTPヘッダから、GET JWTをJWT、セットアップを解析し、このカスタマイズされた設定Authentication
オブジェクトをし、それを設定しますSecurityContext
:
SecurityContextHolder.getContext().setAuthentication(authenication);
このアクセスするにはAuthentication
コントローラー内のオブジェクトを、あなたが使用することができます。
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
CurrentUser user = (CurrentUser) auth.getPrincipal();
CurrentRequestDetail detail= (CurrentRequestDetail) auth.getDetails();
/** CurrentUser and CurrentRequestDetail is the customised Principal and Details**/
あなたがアクセスする必要がある場合は[ Principal
]だけは、使用することができます@AuthenticationPrincipal
:
@PostMapping("")
public Mono<User> login(@RequestBody User post,
@RequestParam String user_id,
@RequestParam String username,
@AuthenticationPrincipal CurrentUser currentUser) {
//Need to access information from JWT claims here
return this.repository.findById(user_id);
}