1

I have a simple requirement to read the token in asp.net core web api for every request and read the sub part of token which has UserID. Token validation will be done by a third party rest api call which will tell if token is valid or not. No validation logic should exist in my api.

Unfortunately all the articles I have read, they are validating the token, which I don't want in my case.

Any help would be much appreciated.

1 Answer 1

1

You can use the following extension method to get userID from HttpContext. Use ClaimType which contains userID value.

public static int GetUserID(this Microsoft.AspNetCore.Http.HttpContext context){
            var claimsIdentity = context.User;
            var claim = claimsIdentity.Claims.FirstOrDefault(cl => cl.Type == ClaimTypes.YOUR_CLAIM_TYPE);            
            return Convert.ToInt32(claim.Value);
        }

Usage in your controller methods:

var userID = HttpContext.GetUserID();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.