Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Spring Boot JWT: how do I get user id, from jwt or request?

In my Spring Boot application (let’s say it is blog app) I am using JWT authentication.

But if I want to create a new post, should I pass the user ID inside the request body? But is it insecure to do so. Because, I should store user id in localstorage in Front end and put it in request before sending.
Or I should get user id from JWT? But, I have to inject that authManager dependency in all my controllers?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Yes, you should get the userId from the JWT token.
The token should be added on all requests and must be validated before the backend do any action.

And you don’t have to add the AuthManager to all of your controllers. You can setup rules with Spring-Security. Have a look at this: https://spring.io/guides/topicals/spring-security-architecture/

At the end: You can inject the AuthManager only at places where you need the username. Or let Spring add the Authentication.

public class YourController {

   @POST
   public void create(@RequestBody Post post, Authentication auth) {
      // from the auth you can extract the users name or id
   }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading