3

I am new to Thymeleaf and currently working on a user management tool with Springboot. First of all the account need to be logged in to see the personal data. My problem is, to get the current logged in username, which is an email in my case and call the Rest-API with the url "/{email}" with Getmapping?

My idea was to Get the securitycontextholder.getcontext().getprincipal() and pass it to a Request call . Finally display the data

this is my GetMappping from the controller layer

 @GetMapping("/{email}")
public ResponseEntity getApplicantByEmail(@PathVariable String email){
    return new ResponseEntity(applicantService.getApplicantByEmail(email), HttpStatus.OK);
}
han chu
  • 41
  • 1
  • 1
    Am I correct that you want: [allow-a-user-only-access-their-own-data-in-spring-boot-spring-security](https://stackoverflow.com/questions/51712724/how-to-allow-a-user-only-access-their-own-data-in-spring-boot-spring-security) – Dirk Deyne Nov 25 '20 at 17:46
  • @DirkDeyne thank you the reply, and yes that's right but my problem is also how to call the request on thymeleaf to display the data – han chu Nov 25 '20 at 17:49
  • Look at this answer to create a link:[create-a-url-based-on-springsecurity-username-in-thymeleaf](https://stackoverflow.com/questions/31113190/create-a-url-based-on-springsecurity-username-in-thymeleaf). Secondly your endpoint should probably return a template (String), or are you planning to access this endpoint via javascript? – Dirk Deyne Nov 25 '20 at 18:16
  • Nicely done for a first question. Clear title, nice description of the problem. I just wish I knew thymeleaf so I could offer an answer. – Jeter-work Nov 25 '20 at 18:28

1 Answers1

0

You can make the current user available to the Thymeleaf model by introducing @ControllerAdvice:

@ControllerAdvice
public class CurrentUserAdvice {
    @ModelAttribute("currentEmailAddress")
    public String emailAddress(Authentication authentication) {
        return authentication.getName();
    }
}

This will make the model attribute currentEmailAddress available in Thymeleaf templates.

If you have a custom domain object as the principal in Authentication, you can make the entire user available in the model using the same pattern:

@ControllerAdvice
public class CurrentUserAdvice {
    @ModelAttribute("currentUser")
    public MyUser user(@AuthenticationPrincipal MyUser user) {
        return user;
    }
}
jzheaux
  • 7,042
  • 3
  • 22
  • 36