spring securityを使ってログイン中のユーザーを取得したり表示したりするための設定が意外と面倒だったため記録
ユーザー情報クラス
@AuthenticationPrincipal
で取得するためにaccountフィールドを追加
AccountDetail.java
import java.util.ArrayList;
import com.example.todo.entity.Account;
import org.springframework.security.core.userdetails.User;
import lombok.Getter;
public class AccountDetail extends User{
// 追記
@Getter
private Account account;
public AccountDetail(Account account){
super(
account.getName(),
account.getPassword(),
true,
true,
true,
true,
new ArrayList<>()
);
// 追記
this.account = account;
}
}
e.g. Controller
-
@AuthenticationPrincipal
を使って取得する @AuthenticationPrincipal(expression = "account") Account account
-
expression = "account"
でUserクラスのaccount
フィールドを参照して取得
import com.example.todo.entity.Account;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
public class TodoController {
@RequestMapping(value="/index")
public String index(@AuthenticationPrincipal(expression = "account") Account account, ...) {
long accountId = account.getId();
...
return "todo/index";
}
@AuthenticationPrincipal(expression = "account") Account account
これで何が起こっているか
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
AccountDetail accountDetail = (AccountDetail) auth.getPrincipal();
Account account = accountDetail.getAccount();
getPrincipal()
でUserクラスにキャストできないためちょっとした設定が必要になるみたいです
画面での表示
Thymeleafでログイン中のユーザーを取得
dependencyの追加
pom.xml
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
Thymeleaf
- htmlタグに
xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
を追加 - 表示したい箇所で
sec:authentication
を使用
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
...
</head>
<body>
<p sec:authentication="name"></p>
</body>
</html>