I am trying to get the UUID from my logged in user to be stored as the "CreatedBy" and "LastUpdatedBy" instead of just the string. However, I am getting a cast error:
class java.lang.String cannot be cast to class com.example.lims.container.Container
All code below...thanks!
BIG EDIT:
I changed ApplicationUser to implement the UserDetails from SpringSecurity and added legit Mapped relationships to my BaseEntity. Now I get a new exception. I'm pretty sure it has to do with what I'm returning from SecurityAuditAware. I don't know how to get it to return the correct ApplicationUser instance.
java.lang.ClassCastException: class java.lang.String cannot be cast to class com.example.lims.user.ApplicationUser (java.lang.String is in module java.base of loader 'bootstrap'; me.tmpjr.lims.user.ApplicationUser is in unnamed module of loader org.springframework.boot.devtools.restart.classloader.RestartClassLoader @3d3e8a83) at com.example.lims.security.SecurityAuditorAware.getCurrentAuditor(SecurityAuditorAware.java:20) ~[classes/:na]
Schema:
CREATE TABLE IF NOT EXISTS "containers" (
id uuid NOT NULL,
container_name VARCHAR(100) NOT NULL,
created_by UUID NOT NULL,
created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL,
updated_by UUID,
updated_at TIMESTAMP WITHOUT TIME ZONE,
PRIMARY KEY (id)
);
CREATE TABLE IF NOT EXISTS "users" (
id uuid NOT NULL,
username VARCHAR(100) NOT NULL,
password VARCHAR(100) NOT NULL,
created_by UUID,
created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL,
updated_by UUID,
updated_at TIMESTAMP WITHOUT TIME ZONE,
PRIMARY KEY (id)
);
BaseEntity AuditorAware:
@Data
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class BaseEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected UUID id;
@CreatedDate
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created_at")
protected Date createdAt;
@LastModifiedDate
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "updated_at")
protected Date updatedAt;
@CreatedBy
@JoinColumn(name = "created_by", nullable = true, insertable = true, updatable = false)
@ManyToOne
protected ApplicationUser createdBy;
@LastModifiedBy
@JoinColumn(name = "updated_by", nullable = true, insertable = false, updatable = false)
@ManyToOne
protected ApplicationUser updatedBy;
}
ApplicationUser:
@Data
@EqualsAndHashCode(callSuper = true)
@Entity
@Valid
@Table(name = "users")
@NoArgsConstructor
public class ApplicationUser extends BaseEntity implements UserDetails
{
@Column(nullable = false)
private String username;
@Column(nullable = false)
private String password;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
@Override
public boolean isAccountNonExpired() {
return false;
}
@Override
public boolean isAccountNonLocked() {
return false;
}
@Override
public boolean isCredentialsNonExpired() {
return false;
}
@Override
public boolean isEnabled() {
return false;
}
}
Security AuditorAware Implementation that returns ApplicationUser:
@Component
public class SecurityAuditorAware implements AuditorAware<ApplicationUser> {
public Optional<ApplicationUser> getCurrentAuditor() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth == null || !auth.isAuthenticated()) {
return Optional.empty();
}
// THIS is where I think it's going wrong.. what to return here? How to return ApplicationUser?
return Optional.ofNullable((ApplicationUser) auth.getPrincipal());
}
}
UserDetailsServiceImpl:
@RequiredArgsConstructor
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
private final ApplicationUserRepository userRepository;
@Override
public ApplicationUser loadUserByUsername(String username) throws UsernameNotFoundException {
ApplicationUser applicationUser = userRepository.findByUsername(username);
if (applicationUser == null) {
throw new UsernameNotFoundException(username);
}
return applicationUser;
}
}
Bean Config:
@Configuration
@EnableJpaAuditing(auditorAwareRef = "auditorAware")
public class PersistenceConfig {
@Bean
public AuditorAware<ApplicationUser> auditorAware() {
return new SecurityAuditorAware();
}
}
Full Exception:
java.lang.ClassCastException: class java.lang.String cannot be cast to class com.example.lims.user.ApplicationUser (java.lang.String is in module java.base of loader 'bootstrap'; com.example.lims.user.ApplicationUser is in unnamed module of loader org.springframework.boot.devtools.restart.classloader.RestartClassLoader @3d3e8a83)
at com.example.lims.security.SecurityAuditorAware.getCurrentAuditor(SecurityAuditorAware.java:21) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
VALID WORKAROUND?
I believe I have found the issue. Since I'm using UsernamePasswordAuthenticationToken getPrinciple does not return a UserDetails object. I simply cannot get it to cast to my custom Entity class. However, if I manually user a repository search inside my SecurityAuditorAware and return it directly it works!
@Component
@RequiredArgsConstructor
public class SecurityAuditorAware implements AuditorAware<ApplicationUser> {
private final ApplicationUserRepository userRepository;
public Optional<ApplicationUser> getCurrentAuditor() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth == null || !auth.isAuthenticated()) {
return Optional.empty();
}
return Optional.ofNullable((ApplicationUser) userRepository.findByUsername((auth.getName())));
}
}