File tree Expand file tree Collapse file tree
main/java/com/vaadin/flow/spring/security
test/java/com/vaadin/flow/spring/security Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1717
1818import java .io .IOException ;
1919import java .io .Serializable ;
20+ import java .security .Principal ;
2021import java .util .List ;
2122import 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 *
Original file line number Diff line number Diff 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 {
You can’t perform that action at this time.
0 commit comments