All Downloads are FREE. Search and download functionalities are using the official Maven repository.

de.coderspack.spring.boot.jwt.library.security.CurrentJwtUser Maven / Gradle / Ivy

package de.coderspack.spring.boot.jwt.library.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Optional;

public class CurrentJwtUser {

   private static final Logger LOG = LoggerFactory.getLogger(CurrentJwtUser.class);

   private CurrentJwtUser() {
   }

   /**
    * Get the login of the current user.
    *
    * @return the login of the current user.
    */
   public static Optional getUsername() {
      final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

      if (authentication == null) {
         LOG.debug("no authentication in security context found");
         return Optional.empty();
      }

      String username = null;
      if (authentication.getPrincipal() instanceof UserDetails) {
         UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
         username = springSecurityUser.getUsername();
      } else if (authentication.getPrincipal() instanceof String) {
         username = (String) authentication.getPrincipal();
      }

      LOG.debug("found username '{}' in security context", username);

      return Optional.ofNullable(username);
   }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy