
ru.mynewtons.starter.oauth2.config.security.audit.UsernameAuditorAware Maven / Gradle / Ivy
package ru.mynewtons.starter.oauth2.config.security.audit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
@Slf4j
public class UsernameAuditorAware implements AuditorAware {
@Override
public String getCurrentAuditor() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || !authentication.isAuthenticated()) {
return null;
}
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof String) {
return (String) principal;
}
if (principal instanceof User) {
User user = (User) principal;
return user.getUsername();
}
if (principal instanceof UserDetails) {
UserDetails userDetails = (UserDetails) principal;
return userDetails.getUsername();
}
if (principal instanceof Authentication) {
Authentication auth = (Authentication) principal;
return auth.getName();
}
log.warn(" Object principal is not String/org.springframework.security.core.userdetails.User/Authentication");
return null;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy