Java Community | Help. Code. Learn.JC|HCL
Java Community | Help. Code. Learn.โ€ข12mo agoโ€ข
3 replies
Victor

Spring security: get user from implementation of UserDetails from Authorization

Im trying to extract the user of a request through the Authorization object.

this is my implementation of UserDetails:

public class UserPrincipal implements UserDetails {

    private final User user;

    public UserPrincipal(User user) {
        this.user = user;
    }

    public User getUser() {
        return user;
    }

//ommited overridden methods

i tried getting the user by downcasting to my implementation and then getting the user but im getting an error that class org.springframework.security.oauth2.jwt.Jwt cannot be cast to class UserPrincipal.

public class ItemMapper {

    UserPrincipal userPrincipal;

    public Item toItem(ItemRequest itemRequest, Authentication authentication) {

        userPrincipal = (UserPrincipal) authentication.getPrincipal();

        return new Item(itemRequest.name(), itemRequest.brand(), itemRequest.condition(),
                itemRequest.price(), itemRequest.size(), userPrincipal.getUser());
    }

}


Am i misunderstading something about the authentication.getPrincipal()? what would be the best way to get the user from the authentication?
Was this page helpful?