- 履歴一覧
- 差分 を表示
- 現在との差分 を表示
- ソース を表示
- Spring Boot/ログインユーザー情報を取得する へ行く。
- 1 (2017-05-25 (木) 16:36:31)
キーワード†
- Spring Boot
- Spring Security
したいこと†
Spring Securityでログインしたログインユーザーの情報(LoggedInUser implements UserDetails)を取得したい。
どうやって†
ControllerAdviceで@ModelAttributeをセットしておくのが楽だと思う。
@ControllerAdvice
public class PrincipalControllerAdvice {
@ModelAttribute
public Manager getLoggedInUser(Principal principal) {
return
Optional.ofNullable(principal)
.filter(p -> p instanceof Authentication).map(p -> (Authentication) p)
.map(a -> a.getPrincipal())
.filter(p -> p instanceof LoggedInUser).map(p -> (LoggedInUser) p)
.orElse(null);
}
}
リクエストハンドラでは@ModelAttributeで取得できる。
@RequestMapping("/nanika")
public String nanika(
@ModelAttribute LoggedInUser loggedInUser,
Model model
) { /* 処理 */ }
ノート†
定形処理はアスペクトにしておくのが吉。