java
52 lines · 8 steps
Injecting the current user in Spring MVC
A custom @CurrentUser annotation plus an argument resolver lets controllers receive the logged-in User directly as a method parameter.
Explained by
highlit
1@Target(ElementType.PARAMETER)
2@Retention(RetentionPolicy.RUNTIME)
3public @interface CurrentUser {
4}
5
6@Component
7public class CurrentUserArgumentResolver implements HandlerMethodArgumentResolver {
8
9 private final UserRepository userRepository;
10
11 public CurrentUserArgumentResolver(UserRepository userRepository) {
12 this.userRepository = userRepository;
13 }
14
15 @Override
16 public boolean supportsParameter(MethodParameter parameter) {
17 return parameter.hasParameterAnnotation(CurrentUser.class)
18 && User.class.isAssignableFrom(parameter.getParameterType());
19 }
20
21 @Override
22 public Object resolveArgument(MethodParameter parameter,
23 ModelAndViewContainer mavContainer,
24 NativeWebRequest webRequest,
25 WebDataBinderFactory binderFactory) {
26 Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
27
28 if (authentication == null || !authentication.isAuthenticated()
29 || authentication instanceof AnonymousAuthenticationToken) {
30 throw new AccessDeniedException("No authenticated user present");
31 }
32
33 String username = authentication.getName();
34 return userRepository.findByUsername(username)
35 .orElseThrow(() -> new UsernameNotFoundException(username));
36 }
37}
38
39@Configuration
40public class WebConfig implements WebMvcConfigurer {
41
42 private final CurrentUserArgumentResolver currentUserArgumentResolver;
43
44 public WebConfig(CurrentUserArgumentResolver currentUserArgumentResolver) {
45 this.currentUserArgumentResolver = currentUserArgumentResolver;
46 }
47
48 @Override
49 public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
50 resolvers.add(currentUserArgumentResolver);
51 }
52}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A custom HandlerMethodArgumentResolver removes boilerplate by turning security context lookups into a clean controller parameter.
- 2Pairing a marker annotation with supportsParameter lets you scope a resolver precisely to the parameters you intend it for.
- 3Custom resolvers only take effect once registered via WebMvcConfigurer.addArgumentResolvers.
Related explainers
java
public class SlidingLogRateLimiter { private final int maxRequests; private final long windowMillis;
How a sliding-log rate limiter works
rate-limiting
concurrency
sliding-window
Advanced
8 steps
typescript
import { Injectable, UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { ConfigService } from '@nestjs/config';
How a JWT strategy authenticates in NestJS
authentication
jwt
passport
Intermediate
7 steps
java
public final class Slugifier { private static final Pattern NON_LATIN = Pattern.compile("[^\\w-]"); private static final Pattern WHITESPACE = Pattern.compile("[\\s]+");
Building a URL slugifier in Java
regex
unicode-normalization
string-processing
Intermediate
8 steps
go
package auth import ( "net/http"
Setting and reading secure session cookies in Go
cookies
session-management
security
Intermediate
6 steps
java
@Repository public interface OrderRepository extends JpaRepository<Order, Long> { @Query("""
Keyset pagination with Spring Data JPA
pagination
cursor
jpa
Advanced
8 steps
python
import os from datetime import timedelta
Class-based config in a Flask app factory
configuration
app-factory
inheritance
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/injecting-the-current-user-in-spring-mvc-explained-java-0892/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.