
# コントローラーで

コントローラーのメソッドは、`SecurityContextHolder` を読まずに、現在のユーザーをパラメーターとして求めることができます。`spring_security_core` のメソッドセキュリティのアノテーション (`@PreAuthorize` など) はコントローラーとサービスで動きます。拒否された呼び出しは `403` になり、ログインしていない呼び出し元にはログインが求められます。

## 使う理由

ハンドラーはしばしばユーザーを必要とします。「自分の注文」を読み込むため、誰が変更したかを記録するためです。パラメーターならそれがシグネチャーに表れ、ハンドラーをテストしやすく保てます。データに依存するルール (注文の所有者) は、URL のルールではなく、コードの隣に `@PreAuthorize` で置くのが適切です。

## 例

```dart
@RestController()
@RequestMapping('/api')
class AccountController {
  AccountController(this.orders);

  final OrderService orders;

  @GetMapping('/me')
  String me(Authentication authentication) => authentication.name;

  // パスワードログイン: 読み込まれた UserDetails。
  @GetMapping('/profile')
  String profile(@AuthenticationPrincipal() UserDetails user) => user.username;

  // リソースサーバー: デコードされたトークン。
  @GetMapping('/tenant')
  String tenant(@AuthenticationPrincipal() Jwt jwt) => jwt.getClaimAsString('tenant') ?? '';

  // シングルサインオン: OpenID Connect のユーザー。
  @GetMapping('/whoami')
  String whoami(@AuthenticationPrincipal() OidcUser? user) => user?.email ?? 'anonymous';

  @DeleteMapping('/orders/{id}')
  @PreAuthorize("hasRole('ADMIN')")
  Future<void> delete(@PathVariable() int id) => orders.delete(id);
}
```

## パラメーター

| パラメーター | 受け取るもの |
|---|---|
| `Authentication authentication` | 現在の `Authentication`。 |
| `Principal principal` | 同じものを `Principal` として (その `name`)。 |
| `@AuthenticationPrincipal() T user` | プリンシパル。パスワードログインの `UserDetails`、Bearer トークンの `Jwt`、シングルサインオンの `OAuth2User` / `OidcUser`、または独自のクラス。 |
| `@CurrentSecurityContext() SecurityContext context` | コンテキストそのもの。その認証が匿名でも、存在しなくても渡される。 |

`@AuthenticationPrincipal` は、ユーザーがいない場合、ユーザーが匿名の場合、プリンシパルがパラメーターの型でない場合に `null` を渡します。`@AuthenticationPrincipal(errorOnInvalidType: true)` では、型が違うとリクエストが失敗します。アクセスルールがそのパスでログインを要求しない限り、パラメーターは nullable にしてください。

## コントローラーのメソッドセキュリティ

`@PreAuthorize`、`@PostAuthorize`、`@Secured`、`@PreFilter`、`@PostFilter` は、他の Bean と同じくコントローラーのメソッドでも動きます ([メソッドセキュリティ](../spring-security-core/method-security.md) を参照)。例外は次の応答になります。

| 例外 | ログインしていない | ログイン済み |
|---|---|---|
| `AccessDeniedException` | ログインを求める: `401`、ブラウザーにはログインページ | `403` |
| `AuthenticationCredentialsNotFoundException` | ログインを求める | |

エラーは `ProblemDetail` ボディ (`application/problem+json`) で、例外のメッセージにはなりません。

## サーバーが描画するページ

`csrfTokenOf(request)` はフォーム用の CSRF トークンを返します ([CSRF](csrf.md) を参照)。

## Spring (Java) との対応

```java
@GetMapping("/profile")
String profile(@AuthenticationPrincipal UserDetails user) { return user.getUsername(); }
```

アノテーションは同じです。Spring はエラーを `/error` に再ディスパッチし、そこではリクエストは匿名です。ここでは `403` か `401` がそのまま応答になります。

## 関連項目

- [メソッドセキュリティ](../spring-security-core/method-security.md)
- [テスト](testing.md)
- [コントローラー](../spring-boot-starter-web/controllers/index.md)
