0

I've seen a lot of code samples that look like this :

@RequestMapping("/user/{id}"}
@PreAuthorize("principal.userId == #id"}
public String getUrl(@PathVariable("id") Long id){

}

I don't understand how it is possible to have access to "userId" from the principal object directly. The only attribute I have access to when I try this is the name.

Spn
  • 410
  • 2
  • 7
  • 16
  • 1
    Does this answer your question? [Spring Security: allow user only to access their own administration page](https://stackoverflow.com/questions/6871203/spring-security-allow-user-only-to-access-their-own-administration-page) – dur Apr 23 '21 at 09:03

1 Answers1

0

The simplest way of doing this in controller is using Authentication object. Try the below code

@RequestMapping("/user"}
public String getUrl(Authentication authentication){
    //Get current logged in user. 
    //If the user not logged in then authentication will be null
    String userName = authentication.getName();
}
Avinash
  • 812
  • 1
  • 8
  • 22