Montag, 29. April 2019

Spring Security - get User Name

If you want to retrieve the name of  a logged in user, do this:


import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
private String getUserName() {
    Object principal = SecurityContextHolder
          .getContext()
          .getAuthentication()
          .getPrincipal();

    String userName;

    if (principal instanceof UserDetails) {
        userName = ((UserDetails)principal).getUsername();
    } else {
        userName = principal.toString();
    }
    return userName;
}

Keine Kommentare:

Kommentar veröffentlichen

NEW BLOG! http://cleancode.consulting/

Dear Reader, This Blog is closed and remains as an archive. Please find our new Blog at  http://cleancode.consulting/