
org.springframework.data.domain.AuditorAwareUserDetails Maven / Gradle / Ivy
package org.springframework.data.domain;
import java.lang.reflect.Field;
import java.util.Optional;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
public class AuditorAwareUserDetails implements AuditorAware {
protected final Log logger = LogFactory.getLog(getClass());
private final UserDetailsService userDetailsService;
private final Class clazz;
public AuditorAwareUserDetails(UserDetailsService userDetailsService, Class clazz) {
this.userDetailsService = userDetailsService;
this.clazz = clazz;
}
/**
*
* authentication != null && authentication.isAuthenticated() && !(authentication instanceof AnonymousAuthenticationToken)
*
*
* @see org.springframework.beans.DirectFieldAccessor#setPropertyValue(String, Object)
*/
@Override
public UserDetails getCurrentAuditor() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authenticationIsRequired(authentication)) {
return null;
}
Object principal = authentication.getPrincipal();
if (principal instanceof UserDetails && this.clazz.isAssignableFrom(principal.getClass())) {
return Optional.ofNullable((UserDetails) principal).get();
}
try {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(authentication.getName());
Field field = ReflectionUtils.findField(authentication.getClass(), "principal");
Assert.notNull(field, "Not Found Field 'pricipal' from... " + authentication.getClass());
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field, authentication, userDetails);
SecurityContextHolder.getContext().setAuthentication(authentication);
return Optional.ofNullable(userDetails).get();
}
catch (UsernameNotFoundException e) {
if (logger.isWarnEnabled()) {
logger.warn("Not found UserDetails from... " + authentication + " " + e);
}
return null;
}
}
/**
* @see org.springframework.security.web.authentication.www.BasicAuthenticationFilter#authenticationIsRequired(String)
*/
private boolean authenticationIsRequired(Authentication existingAuth) {
if (existingAuth == null || !existingAuth.isAuthenticated()) {
return true;
}
if (existingAuth instanceof AnonymousAuthenticationToken) {
return true;
}
return false;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy