java 108 lines · 4 tabs

Resolve the Authenticated User into a Controller Argument in Spring Boot

Shared by codesnips Aug 2026
4 tabs
package com.example.security;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface CurrentUser {
}
4 files · java Explain with highlit

This snippet shows the idiomatic Spring MVC pattern for injecting the current authenticated user directly into a controller method as a typed argument, instead of reaching into SecurityContextHolder from inside every handler. The mechanism is a HandlerMethodArgumentResolver, the same SPI Spring uses to resolve @RequestParam, @PathVariable, and @RequestBody — custom resolvers plug into that pipeline so controllers stay clean and testable.

The @CurrentUser annotation is a small marker with @Target(ElementType.PARAMETER) so it can only decorate method arguments. It carries no behavior itself; it exists so the resolver can identify which parameters it is responsible for. Keeping it a distinct annotation (rather than reusing a type check) means intent is explicit at the call site and the resolver never accidentally hijacks an unrelated AuthUser parameter.

In CurrentUserArgumentResolver, supportsParameter returns true only when the parameter is annotated with @CurrentUser and its type is AuthUser, which is how Spring decides to route resolution here. resolveArgument then pulls the Authentication from the SecurityContext. It deliberately guards against the anonymous case: if there is no authentication, it is not authenticated, or the principal is the literal string "anonymousUser", the method returns null rather than a bogus user. The happy path casts the principal to the application's AuthUser and returns it. Casting the principal assumes the security filter chain populated the context with an AuthUser — a fair assumption when a JWT filter builds that principal during authentication.

WebConfig wires the resolver in through WebMvcConfigurer.addArgumentResolvers; without this registration the annotation is inert. Because the resolver is a Spring bean, it can hold collaborators like repositories if richer lookups are needed.

Finally, AccountController demonstrates the payoff: me and updateProfile simply declare @CurrentUser AuthUser user and receive a fully resolved principal. A subtle pitfall is that returning null for anonymous requests means endpoints must still be protected by Spring Security; the resolver is a convenience, not an authorization boundary. This approach shines when many controllers need the current user and the team wants to avoid repetitive boilerplate and brittle manual casts.


Related snips

ruby
payload = {
  sub: user.id,
  iss: 'https://auth.example.com',
  aud: 'codesnips-api',
  exp: 15.minutes.from_now.to_i,
  iat: Time.now.to_i,

JWT issuance and verification without common footguns

jwt authentication api
by Kai Nakamura 2 tabs
graphql
type User {
    id: ID!
    name: String!
    email: String!
    posts: [Post!]!
    createdAt: String!

GraphQL API with Spring Boot

java graphql spring-boot
by David Kumar 3 tabs
ruby
class SignupForm
  include ActiveModel::Model
  include ActiveModel::Attributes

  attribute :account_name, :string
  attribute :email, :string

Shallow Controller, Deep Params: Form Object Pattern

rails activemodel form-object
by codesnips 3 tabs
javascript
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = ["form"]
  static values = { delay: { type: Number, default: 250 } }

Debounced live search with Stimulus + Turbo Streams

rails hotwire stimulus
by codesnips 4 tabs
java
package com.example.starter.config;

import com.example.starter.properties.CustomProperties;
import com.example.starter.service.CustomService;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;

Custom Spring Boot starters

java spring-boot starter
by David Kumar 4 tabs
bash
#!/usr/bin/env bash
set -euo pipefail

export VAULT_ADDR="https://vault.internal:8200"
export VAULT_TOKEN="${VAULT_TOKEN:?missing VAULT_TOKEN}"

Secrets management with environment isolation and Vault

secrets-management vault environment-variables
by Kai Nakamura 1 tab

Share this code

Here's the card — post it anywhere.

Resolve the Authenticated User into a Controller Argument in Spring Boot — share card
Link copied