Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oauth2 get Username from token

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

like image 879
RK3 Avatar asked Jul 22 '18 08:07

RK3


People also ask

Should access token contain user ID?

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.

How can I check my OAuth token?

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.


1 Answers

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();
}
like image 51
MyTwoCents Avatar answered Sep 20 '22 15:09

MyTwoCents