0
1

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これで何が起こっているか

  1. Authentication auth = SecurityContextHolder.getContext().getAuthentication();
  2. AccountDetail accountDetail = (AccountDetail) auth.getPrincipal();
  3. 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>
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1