
# In controllers

A controller method can ask for the current user as a parameter, without reading `SecurityContextHolder`. Method security annotations of `spring_security_core` (`@PreAuthorize` and the others) work on controllers and services; a denied call becomes a `403`, and a caller who is not logged in is asked to log in.

## Why

Handlers often need the user: to load "my orders", to stamp who made a change. A parameter says it in the signature and keeps the handler easy to test. Rules that depend on the data (an order's owner) belong next to the code, with `@PreAuthorize`, rather than in URL rules.

## Example

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

  final OrderService orders;

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

  // A password login: the loaded UserDetails.
  @GetMapping('/profile')
  String profile(@AuthenticationPrincipal() UserDetails user) => user.username;

  // A resource server: the decoded token.
  @GetMapping('/tenant')
  String tenant(@AuthenticationPrincipal() Jwt jwt) => jwt.getClaimAsString('tenant') ?? '';

  // Single sign-on: the OpenID Connect user.
  @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);
}
```

## Parameters

| Parameter | Receives |
|---|---|
| `Authentication authentication` | The current `Authentication`. |
| `Principal principal` | The same, as a `Principal` (its `name`). |
| `@AuthenticationPrincipal() T user` | The principal: the `UserDetails` of a password login, the `Jwt` of a bearer token, the `OAuth2User` / `OidcUser` of single sign-on, or your own class. |
| `@CurrentSecurityContext() SecurityContext context` | The context itself, even when its authentication is anonymous or missing. |

`@AuthenticationPrincipal` gives `null` when there is no user, when the user is anonymous, or when the principal is not of the parameter's type. With `@AuthenticationPrincipal(errorOnInvalidType: true)` a wrong type fails the request instead. Make the parameter nullable unless the access rules require a login for the path.

## Method security on controllers

`@PreAuthorize`, `@PostAuthorize`, `@Secured`, `@PreFilter` and `@PostFilter` work on controller methods as on any bean (see [Method security](../spring-security-core/method-security.md)). The exceptions become answers:

| Exception | Not logged in | Logged in |
|---|---|---|
| `AccessDeniedException` | asked to log in: `401`, or the login page for a browser | `403` |
| `AuthenticationCredentialsNotFoundException` | asked to log in | |

Errors are `ProblemDetail` bodies (`application/problem+json`), never the exception's message.

## Pages rendered by the server

`csrfTokenOf(request)` gives the CSRF token for a form (see [CSRF](csrf.md)).

## In Spring (Java)

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

The same annotations. Spring re-dispatches errors to `/error`, where the request is anonymous; here the `403` or `401` is the answer.

## See also

- [Method security](../spring-security-core/method-security.md)
- [Testing](testing.md)
- [Controllers](../spring-boot-starter-web/controllers/index.md)
