I have implemented Ouath2 as security for my Spring boot rest controllers. Before any of my resource is called, oauth2 validates the token for the users in user table. My question is how to avoid situation where if user1 token is in the request and the request body has data for user2 modification? I need to put a check such that User1 with his token should be able to modify data only for himself. If user1 with his toekn has user2 data in request body should throw 403.
I was thinking if i can get username from token at service layer to do this check? Any help appreciated
Note that the token does not contain any information about the user besides their ID (sub claim). It only contains authorization information about which actions the application is allowed to perform at the API (scope claim). This is what makes it useful for securing an API, but not for authenticating a user.
The token can be verified via introspect endpoint or by signature. The most common way to build built-in token verification into the system is to introspect the token on the API Gateway and verify the signature on other services.
You are using Spring Security for authentication.
You can get User Detail from SecurityContext
Authentication authentication = SecurityContextHolder.getContext()
.getAuthentication();
UserDetails userDetail = authentication.getPrincipal();
userDetail.getUsername();
or in Rest Controller
@RequestMapping(value = "/username", method = RequestMethod.GET)
public String currentUserName(Principal principal) {
return principal.getName();
}
or
@RequestMapping(value = "/username", method = RequestMethod.GET)
public String currentUserName(HttpServletRequest request) {
Principal principal = request.getUserPrincipal();
return principal.getName();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With