dev mobile
dev mobile

Reputation: 33

get User from String bearer token

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;
        }

Upvotes: 0

Views: 60

Answers (1)

aitchdot
aitchdot

Reputation: 503

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;
        ...
    }
}

Upvotes: 0

Related Questions