Manually decode OAuth bearer token in c#

前端 未结 3 1588
走了就别回头了
走了就别回头了 2021-02-07 18:51

In my Web Api 2.2 OWIN based application I have a situation where I manually need to decode the bearer token but I don\'t know how to do this. This is my startup.cs

<         


        
3条回答
  •  情歌与酒
    2021-02-07 19:42

    You can read JWT and create Principals and Identity object using the System.IdentityModel.Tokens.Jwt package - https://www.nuget.org/packages/System.IdentityModel.Tokens.Jwt/.

    Here's a quick example that shows the options available when reading and validating the token,

        private ClaimsIdentity GetIdentityFromToken(string token, X509Certificate2 certificate)
        {  
            var tokenDecoder = new JwtSecurityTokenHandler();         
            var jwtSecurityToken = (JwtSecurityToken)tokenDecoder.ReadToken(token);
    
            SecurityToken validatedToken;
    
            var principal = tokenDecoder.ValidateToken(
                jwtSecurityToken.RawData,
                new TokenValidationParameters()
                    {
                        ValidateActor = false,
                        ValidateIssuer = false,
                        ValidateAudience = false,
                        ValidateLifetime = false,
                        ValidateIssuerSigningKey = false,
                        RequireExpirationTime = false,
                        RequireSignedTokens = false,
                        IssuerSigningToken = new X509SecurityToken(certificate)
                    },
                out validatedToken);
    
            return principal.Identities.FirstOrDefault();
        }
    

提交回复
热议问题