0

we have a method that validates token and takes the user from Bearer token, but this method is not authorized, so how we retrieve the User data from string token

   private static bool ValidateToken(string authToken)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var validationParameters = GetValidationParameters();

            SecurityToken validatedToken;
            IPrincipal principal = tokenHandler.ValidateToken(authToken, validationParameters, out validatedToken);


//Get ID from Token

var isValid = GetValidId(id)

            return true;
        }
1
  • "but this method is not authorized" you meant the Token is invalid? Commented Oct 16, 2024 at 10:33

1 Answer 1

0

Assuming it's named id in the claims:

var identity = principal.Identity as ClaimsIdentity;
if (identity != null && identity.IsAuthenticated)
{
    var idClaim = identity.FindFirst("id");
    if (idClaim != null)
    {
        string id = idClaim.Value;
        ...
    }
}

If it's really about getting the id without validating:

if (tokenHandler.CanReadToken(authToken))
{
    var jwtToken = tokenHandler.ReadJwtToken(authToken);

    var idClaim = jwtToken.Claims.FirstOrDefault(c => c.Type == "id");
    if (idClaim != null)
    {
        string id = idClaim.Value;
        ...
    }
}
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.