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
-
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 (); }
Related questions
- java : Overriding the Spring security login page
- java : How to get the data that the user enters on the login page?
- java : Spring Boot Security, how to set up Russian login?
- java : FindByUsername JpaRepository doesn't work
- java : Transition not firing after Spring Security authorization
- java : Encoded password does not look like BCrypt (Spring Security)
- Java Why does Spring -Tomcat close all connections it has created?
- java : Getting value from JSP form to method
- java : Incorrect time (time zone) in the response
hello Principal principal is very succinct user information. try like this