Milad
Milad

Reputation: 592

How to update the currently available UserDetails object in security context in Spring boot

I have implemented a UserDetails object. My implementation of UserDetails object contains First Name, Last Name, Email and image.

I have a user profile area which user uploads his/her new image. when the upload completes i want to update the image property of the currently available UserDetails object in security context.

UserDetails implementation :

public class CustomeUserDetails implements UserDetails {
private Long id;

private String firstName;

private String lastName;

private String email;

private String password;

private String image;

private Boolean isSocialMediaUser;

private List<String> userRoles;

public CustomeUserDetails(User user , List<String> userRoles) {
    this.firstName = user.getUserProfile().getFirstName();
    this.lastName = user.getUserProfile().getLastName();
    this.email = user.getEmail();
    this.password = user.getPassword();
    this.id = user.getId();
    this.image = user.getUserProfile().getImageFileName();
    this.isSocialMediaUser = user.getSocialMediaUser();
    this.userRoles = userRoles;
}

public Long getId() {
    return id;
}

public String getFirstName() {
    return firstName;
}

public String getLastName() {
    return lastName;
}

public String getEmail() {
    return email;
}

public String getImage() {
    return image;
}

public Boolean getSocialMediaUser() {
    return isSocialMediaUser;
}

@Override
public String getPassword() {
    return password;
}

@Override
public String getUsername() {
    return getEmail();
}

@Override
public boolean isAccountNonExpired() {
    return true;
}

@Override
public boolean isAccountNonLocked() {
    return true;
}

@Override
public boolean isCredentialsNonExpired() {
    return true;
}

@Override
public boolean isEnabled() {
    return true;
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    if(userRoles.isEmpty()){
        userRoles.add("ROLE_STANDARD");
    }
    return AuthorityUtils.createAuthorityList(userRoles.stream().toArray(String[]::new));
}

Is there anyway to do it?

Thank you in advance.

Upvotes: 0

Views: 1763

Answers (1)

ninj
ninj

Reputation: 1549

I'll be honest, I'm not entirely sure what you want to do is safe, but here's the way the security context is set in BasicAuthenticationFilter:

UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                        /* ... */);
SecurityContextHolder.getContext().setAuthentication(authResult);

You can use your CustomeUserDetails as the principal when constructing the UsernamePasswordAuthenticationToken.

Still, really not sure if this is a safe thing to do.

Upvotes: 2

Related Questions