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?
>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
}
}