Base solution for your next web application
Open Closed

AspNetZero Core | Login with string jwt token | Validate jwt #4805


User avatar
0
ajayak created

Hi,

I am integrating AspNetZero Core app with 3rd party app. For Auth, the only option available is to send jwt token to the external service which will return the token back to me after integration.

Now, I need to verify which user made the request. I have the jwt token as a method argument(query string). How can I exchange this token for User object or how can I make sure that this token is generated by my app and has not tampered?


2 Answer(s)
  • User Avatar
    0
    ajayak created

    Got it done!

    public JwtSecurityToken GetSecurityToken(string token)
            {
                try
                {
                    var securityKey = new SymmetricSecurityKey(Encoding.Default.GetBytes(_configuration["Authentication:JwtBearer:SecurityKey"]));
    
                    var validationParameters =
                        new TokenValidationParameters
                        {
                            ValidIssuer = _configuration["Authentication:JwtBearer:Issuer"],
                            ValidAudiences = new[] { _configuration["Authentication:JwtBearer:Audience"] },
                            IssuerSigningKey = securityKey
                        };
                    var handler = new JwtSecurityTokenHandler();
                    handler.ValidateToken(token, validationParameters, out var jwt);
                    return jwt.As<JwtSecurityToken>();
                }
                catch (Exception e)
                {
                    Logger.Error(L("TokenDecodingFailed"), e);
                    throw new UserFriendlyException(L("UnAuthorizedOperation"));
                }
            }
    
  • User Avatar
    0
    alper created
    Support Team

    Congrats! And thanks for sharing ;)