0

I am developing a simple todo application with Spring Boot. I am using JWT for authorisation. All todos belongs to a user will be get with following endpoint.

@GetMapping("")
public List<Todo> todos(){
    //get username from token
    //return todos belongs to user
}

I have two problems in here:

  1. Is getting username from token a good practise?
  2. What is the best way accessing username with token from a controller class or a service class?

This answer shows how to reach token from controller class. but what if we want to reach token from service class? This answer shows it. But the class is deprecated.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
yusuf
  • 51
  • 5
  • does this help https://stackoverflow.com/questions/49529760/springboot-get-username-from-authentication-via-controller – JCompetence Apr 05 '22 at 07:39

1 Answers1

0

you can get username like this:

UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication()
                        .getPrincipal();
String username = userDetails.getUsername();
erfanmorsali
  • 155
  • 7