Home>

I'm trying to get the details of an authenticated user, but when viewed in debug mode, I get:principal: "anonymousUser"... How can I get to the id of the authorized user?

Authentication auth= SecurityContextHolder.getContext (). getAuthentication ();
Object pricipal= auth.getPrincipal ();
Integer user;
if (pricipal instanceof UserEntity) {
    user= ((UserEntity) pricipal) .getId ();
}

UserEntity

@Entity
@Table (name= "user_table")
@Data
public class UserEntity {
    @Id
    @GeneratedValue (strategy= GenerationType.IDENTITY)
    private Integer id;
    private String activationCode;
    @Column
    private String login;
    @Column
    @NotBlank (message= "Password cannot be empty")
    @Size (min= 10)
    private String password;
    public String getActivationCode () {
        return activationCode;
    }
    public String getRoles () {
        return roleEntity.getName ();
    }
    public void setActivationCode (String activationCode) {
        this.activationCode= activationCode;
    }
    @ManyToOne
    @JoinColumn (name= "role_id")
    private RoleEntity roleEntity;
}
  • Answer # 1

    hello Principal principal is very succinct user information. try like this

    @GetMapping ("/")
      public String daoTestPage (Principal principal) {
     User user= userService.findByUsername (principal.getName ()). OrElseThrow (() ->
     new RuntimeException ("unable to fing user by username:" + principal.getName ()));
    return "authenticated:" + user.getUsername () + ":" + user.getEmail () + ":" + user.getId ();
        }
    
  • Answer # 2

    hello Principal principal is very succinct user information. try like this

    @GetMapping ("/")
      public String daoTestPage (Principal principal) {
     User user= userService.findByUsername (principal.getName ()). OrElseThrow (() ->
     new RuntimeException ("unable to fing user by username:" + principal.getName ()));
    return "authenticated:" + user.getUsername () + ":" + user.getEmail () + ":" + user.getId ();
        }