Asp.net-Web-Api

無法從“Microsoft.IdentityModel.Tokens.SymmetricSecurityKey”轉換為“Microsoft.IdentityModel.Tokens.SigningCredentials”

  • February 26, 2018

在以下教程 使用 Web API 和 Jwt 創建具有身份驗證的 RESTful API 時,我無法讓CustomJwtFormat類編譯:

using System.IdentityModel.Tokens;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.DataHandler.Encoder;
using Thinktecture.IdentityModel.Tokens;

namespace BooksAPI.Identity
{    
   public class CustomJwtFormat : ISecureDataFormat<AuthenticationTicket>
   {
       private static readonly byte[] _secret =              
            TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["secret"]);
       private readonly string _issuer;

       public CustomJwtFormat(string issuer)
       {
           _issuer = issuer;
       }

       public string Protect(AuthenticationTicket data)
       {
           if (data == null)
               throw new ArgumentNullException(nameof(data));

           var signingKey = new HmacSigningCredentials(_secret);
           var issued = data.Properties.IssuedUtc;
           var expires = data.Properties.ExpiresUtc;

           return new JwtSecurityTokenHandler().WriteToken(
              new JwtSecurityToken( _issuer, null, data.Identity.Claims,
                  issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingKey));
       }

       public AuthenticationTicket Unprotect(string protectedText) {
           throw new NotImplementedException();
       }
   }
}

我得到的建構錯誤是:

無法從“Thinktecture.IdentityModel.Tokens.HmacSigningCredentials”轉換為“Microsoft.IdentityModel.Tokens.SigningCredentials”

在搜尋了這個之後,我發現了這個 SO 文章:

ASP.NET v5 多重簽名證書

我已經嘗試了答案文章中的建議,但無濟於事。我點擊了連結:

不明確的參考問題(Microsoft.AspNet.Identity & Microsoft.AspNet.Identity.Core)

但我仍然看到衝突。我應該使用哪個包和命名空間組合?

我遇到了同樣的問題。您必須使用舊版本的 System.IdentityModel.Tokens.Jwt。

打開 nuget 包管理器控制台並執行:

Install-Package System.IdentityModel.Tokens.Jwt -Version 4.0.2.206221351

原始方法:

var signingKey = new HmacSigningCredentials(_secret);

新方法:

var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(_secret);
var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(
           securityKey,SecurityAlgorithms.HmacSha256Signature);
       //---
var issued = data.Properties.IssuedUtc;
var expires = data.Properties.ExpiresUtc;
var token = new JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingCredentials);

引用自:https://stackoverflow.com/questions/41963934