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
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());
}

}
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?
1 Reply
JavaBot
JavaBot2mo ago
This post has been reserved for your question.
Hey @Victor! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically marked as dormant after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here. 💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.

Did you find this page helpful?