令牌处理程序无法将令牌转换为jwt令牌

时间:2019-02-20 04:11:25

标签: asp.net asp.net-web-api2 jwt

我正在尝试使用“ JwtSecurityTokenHandler”将令牌字符串转换为jwt令牌。但是,出现错误消息:“ IDX12709:CanReadToken()返回false。JWT格式不正确:'[PII被隐藏]'。\ n令牌必须采用JWS或JWE紧凑序列化格式。(JWS):'EncodedHeader.EndcodedPayload.EncodedSignature'(JWE):'EncodedProtectedHeader.EncodedEncryptedKey.EncodedInitializationVector.EncodedCiphertext.EncodedAuthenticationTag'。问题如何解决?

这是我的令牌: “eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImFkbWluIiwibmJmIjoxNTUwNjM3NzcxLCJleHAiOjE1NTA2Mzg5NzEsImlhdCI6MTU1MDYzNzc3MX0.tUcoyoHgkrX3rDKl0cRLd9FwLtRprQpgYepMoiekixY”

var tokenHandler = new JwtSecurityTokenHandler();
var jwtToken = tokenHandler.ReadToken(token) as JwtSecurityToken;

调用网络api

using (HttpClient client = new HttpClient())
            {
                string path = "UserMaintenance/ValidateUserId?userid=" + txtUsername.Text.Trim().ToString();
                client.BaseAddress = new Uri(GlobalData.BaseUri);
                client.DefaultRequestHeaders.Add("Authorization", "Bearer" + GlobalData.Token);
                HttpResponseMessage response = client.GetAsync(path).Result;
                if (response.IsSuccessStatusCode)
                {
                    var value = response.Content.ReadAsStringAsync().Result;
                    isValid = JsonConvert.DeserializeObject<bool>(value);
                }
            }

这是我的GetPrincipal方法

public static ClaimsPrincipal GetPrincipal(string token)
    {
        try
        {
            var symmetricKey = Convert.FromBase64String(Secret);
            var validationParameters = new TokenValidationParameters()
            {
                RequireExpirationTime = true,
                ValidateIssuer = false,
                ValidateAudience = false,
                IssuerSigningKey = new SymmetricSecurityKey(symmetricKey)
            };

            var handler = new JwtSecurityTokenHandler();
            handler.InboundClaimTypeMap.Clear();

            SecurityToken securityToken;
            var principal = handler.ValidateToken(token, validationParameters, out securityToken);

            return principal;
        }

        catch (Exception ex)
        {
            return null;
        }
    }

2 个答案:

答案 0 :(得分:2)

这是我的工作方式,它对我有用:

var token = new System.IdentityModel.Tokens.JwtSecurityToken(jwt);  

除非您的令牌格式不正确。如果您也共享令牌,那会更好。

更新:

您还需要从令牌的开头删除单词“ bearer” (如果没有):

 var jwt = context.Request.Headers["Authorization"].Replace("Bearer ", string.Empty);

答案 1 :(得分:0)

版本5.6.0.0-当前是最新版本 可以使用与@ thilim9问题类似的代码。

start(Stage stage)