Skip to content

Commit 2b3eefa

Browse files
authored
feat: Make current user available without an AuthenticationContext instance (#21503)
Makes it possible to write an application method like ``` public static Optional<User> getCurrentUser() { return AuthenticationContext.getCurrentAuthenticatedUser(AppUserInfo.class).map(AppUserInfo::user); } ``` instead of re-implementing everything from AuthenticationContext
1 parent 6428f99 commit 2b3eefa

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

vaadin-spring/src/main/java/com/vaadin/flow/spring/security/AuthenticationContext.java

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,27 @@ public class AuthenticationContext {
9292
* {@code userType}.
9393
*/
9494
public <U> Optional<U> getAuthenticatedUser(Class<U> userType) {
95+
return getCurrentAuthenticatedUser(userType);
96+
}
97+
98+
/**
99+
* Gets an {@link Optional} with an instance of the current user if it has
100+
* been authenticated, or empty if the user is not authenticated.
101+
*
102+
* Anonymous users are considered not authenticated.
103+
*
104+
* @param <U>
105+
* the type parameter of the expected user instance
106+
* @param userType
107+
* the type of the expected user instance
108+
* @return an {@link Optional} with the current authenticated user, or empty
109+
* if none available
110+
* @throws ClassCastException
111+
* if the current user instance does not match the given
112+
* {@code userType}.
113+
*/
114+
public static <U> Optional<U> getCurrentAuthenticatedUser(
115+
Class<U> userType) {
95116
return getAuthentication().map(Authentication::getPrincipal)
96117
.map(userType::cast);
97118
}

0 commit comments

Comments
 (0)