2017-01-31 35 views
6

Podczas samouczku Create a RESTful API with authentication using Web API and Jwt Mam kłopot klasę CustomJwtFormat skompilować:nie można przekonwertować z „Microsoft.IdentityModel.Tokens.SymmetricSecurityKey” do „Microsoft.IdentityModel.Tokens.SigningCredentials”

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

budować błąd dostaję to:

nie można przekonwertować z 'Thinktecture.IdentityModel.Tokens.HmacSigningCredentials' do „Microsoft.IdentityModel.Tokens.SigningCredential s'

Po szukał to znalazłem to SO postu:

ASP.NET v5 Multiple SigningCredentials

Próbowałem zalecenie w poście odpowiedzi, ale bezskutecznie. I po link:

Ambiguous reference issue (Microsoft.AspNet.Identity & Microsoft.AspNet.Identity.Core)

Ale jestem wciąż widząc konflikt. Którą kombinację pakietu i przestrzeni nazw powinienem użyć?

Odpowiedz

16

Wpadłem na ten sam problem. Należy użyć starszej wersji System.IdentityModel.Tokens.Jwt.

otwarty Nuget konsola menedżer pakietów i uruchomić:

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

oryginalna metoda:

var signingKey = new HmacSigningCredentials(_secret); 

nowa metoda:

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); 
Powiązane problemy