Skip to content

Commit 63c63a8

Browse files
authored
feat: added method to get authenticate principal name (#15487)
Principal name usually refers to a user identifier that can be used to retrieve additional details. Fixes #15484
1 parent dcd2f51 commit 63c63a8

2 files changed

Lines changed: 36 additions & 0 deletions

File tree

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

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
import java.io.IOException;
1919
import java.io.Serializable;
20+
import java.security.Principal;
2021
import java.util.List;
2122
import java.util.Optional;
2223

@@ -79,6 +80,22 @@ public <U> Optional<U> getAuthenticatedUser(Class<U> userType) {
7980
.map(userType::cast);
8081
}
8182

83+
/**
84+
* Gets an {@link Optional} containing the authenticated principal name, or
85+
* an empty optional if the user is not authenticated.
86+
*
87+
* The principal name usually refers to a username or an identifier that can
88+
* be used to retrieve additional information for the authenticated user.
89+
*
90+
* Anonymous users are considered not authenticated.
91+
*
92+
* @return an {@link Optional} containing the authenticated principal name
93+
* or an empty optional if not available.
94+
*/
95+
public Optional<String> getPrincipalName() {
96+
return getAuthentication().map(Principal::getName);
97+
}
98+
8299
/**
83100
* Indicates whether a user is currently authenticated.
84101
*

‎vaadin-spring/src/test/java/com/vaadin/flow/spring/security/AuthenticationContextTest.java‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,25 @@ public void getAuthenticatedUser_loggedUserWrongUserType_throws() {
9595
.getAuthenticatedUser(AuthenticatedPrincipal.class));
9696
}
9797

98+
@Test
99+
public void getPrincipalName_notAuthenticated_getsEmpty() {
100+
Assert.assertTrue(authContext.getPrincipalName().isEmpty());
101+
}
102+
103+
@Test
104+
@WithAnonymousUser
105+
public void getPrincipalName_anonymous_getsEmpty() {
106+
Assert.assertTrue(authContext.getPrincipalName().isEmpty());
107+
}
108+
109+
@Test
110+
@WithMockUser(username = "the-username")
111+
public void getPrincipalName_loggedUser_getsAuthenticationName() {
112+
Optional<String> maybePrincipalName = authContext.getPrincipalName();
113+
Assert.assertTrue(maybePrincipalName.isPresent());
114+
Assert.assertEquals("the-username", maybePrincipalName.get());
115+
}
116+
98117
@Test
99118
@WithMockUser()
100119
public void logout_handlersEngaged() throws Exception {

0 commit comments

Comments
 (0)