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

autoconfigure.com.pannoniaexpertise.audit.PrincipalUsernameProvider Maven / Gradle / Ivy

The newest version!
package autoconfigure.com.pannoniaexpertise.audit;

import com.pannoniaexpertise.audit.AuditUsernameProvider;
import com.pannoniaexpertise.audit.usernameProviders.UsernameProvider;
import java.util.List;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

public class PrincipalUsernameProvider implements AuditUsernameProvider {

  private final List usernameProviders;

  public PrincipalUsernameProvider(final List usernameProviders) {
    this.usernameProviders = usernameProviders;
  }

  @Override
  public String getUsername() {
    final SecurityContext context = SecurityContextHolder.getContext();
    if (context == null) {
      throw new UsernameProviderException("Security context not found");
    }
    final Authentication authentication = context.getAuthentication();
    if (authentication == null) {
      throw new UsernameProviderException("Authentication not found in security context");
    }
    final Object principal = authentication.getPrincipal();
    if (principal == null) {
      throw new UsernameProviderException("User not found in SecurityContext");
    }

    for (UsernameProvider usernameProvider : usernameProviders) {
      if (usernameProvider.support(principal)) {
        return usernameProvider.getUsername(principal);
      }
    }

    try {
      return (String) principal;
    } catch (ClassCastException e) {
      throw new UsernameProviderException(
          "Could not cast principal to string, please provide a custom "
              + principal.getClass().getSimpleName()
              + " implementation of UsernameProvider");
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy