目次
前提
- 認証周りの設定ができている
- Spring securityの認証周りの設定はこちらを参考にすると良いと思います
- https://www.bezkoder.com/spring-boot-jwt-authentication/
- Spring bootでJSON返却するAPIを想定
ログインしているユーザー情報を取得
Controllerの関数で、@AuthenticationPrincipalアノテーションを付けたUserDetailsクラスの引数を設定することで、ここにログインしているユーザー情報が入ってきます。
@GetMapping("/1")
public ResponseEntity<TestRes> test1(@AuthenticationPrincipal UserDetails user) {
return ResponseEntity.ok().body(new TestRes(user.getUsername()));
}
UserDetailsの実装クラスを指定することも可能です。UserDetailsImplの部分はそれぞれの環境で異なると思います。
@GetMapping("/2")
public ResponseEntity<TestRes> test2(@AuthenticationPrincipal UserDetailsImpl user) {
return ResponseEntity.ok().body(new TestRes(String.valueOf(user.getId())));
}
また、WebSecurityConfig#configure()でpermitAll()になっているようなログインが不要なリクエストで指定してしまった場合は、user引数がnullになります。
Spring bootで認証周り含めたサンプルAPI実装しているリポジトリ作っているのでよかったら見てみてください。