user1577242
user1577242

Reputation: 413

OAUTH2 how can I take the username if I have access or refresh_Token

I have a C# application which is using oauth2 to connect to a third party application . First the user is redirected to an external application (ERP) where he enter username and password and an access token which is valid for 1h and a refresh token which is valid 50 years is generated. I'm using this refresh token from my application and based on this I'm getting a new access token.I have the ClientId and ClientSecret. Can I get the logged username having this 2 tokens?

Request :
POST /connect/token HTTP/1.1
Authorization: Basic base64(client_id:client_secret)
Content-Type: application/x-www-form-urlencoded;charset=UTF-8

"grant_type=refresh_token&refresh_token=<refresh_token>"

Response:
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8

{
  "access_token": <access_token>,
  "refresh_token": <refresh_token>,
  "token_type":"bearer",
  "expires_in":3600
}

Upvotes: 2

Views: 689

Answers (2)

Kavindu Dodanduwa
Kavindu Dodanduwa

Reputation: 13059

If you receive the token in a JSON Web Token format (usually called a self-contained access token), then you can decode the token payload and obtain username. Usually, this can be set as the subject ("sub") claim or it can be sent as a dedicated claim in the JWT. Refer this link to understand about JWT claims.

If this is not the case, which means access token is opaque, then you require to use token introspection endpoint. You need to verify such endpoint is provided by your authorization server (the external party which provide you access token). If so, you can invoke the introspection endpoint and obtain token details. This response is used to verify the validity of access token as well as to obtain claims such as username. Please read more about introspection response from this link.

Alternatively, you can switch to [OpenID Connect] (OIDC)3. This will include an ID token in the token response, which is a JWT. You can use this to obtain username (+ other user information) and authenticate the end user on top of JWT validation. Verify whether OIDC is supported by your authorization sever.

Regarding refresh token, you have to have a valid access token or a valid token response to obtain all above. Refresh does not have any meaning for your application other than for getting a new, updated tokens.

Upvotes: 1

D4RKCIDE
D4RKCIDE

Reputation: 3426

You can try something like decoding your token with one of the libraries on jwt.io you can test it out by copying and pasting your token into the site and seeing if your token contains the information you need. then if you scroll down there are many libraries you can use to decode tokens in your code. Take a look at Microsoft's official library here which can also be installed via nuget package manager Install-Package System.IdentityModel.Tokens.Jwt

Upvotes: 0

Related Questions