在遵循教程时
Create a RESTful API with authentication using Web API and Jwt我在编译 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();
}
}
}
我遇到的构建错误是:
Cannot convert from 'Thinktecture.IdentityModel.Tokens.HmacSigningCredentials' to 'Microsoft.IdentityModel.Tokens.SigningCredentials'
搜索后我发现了这个帖子:
ASP.NET v5 Multiple SigningCredentials
我已经尝试了答案帖子中的建议,但没有成功。我点击了链接:
Ambiguous reference issue (Microsoft.AspNet.Identity & Microsoft.AspNet.Identity.Core)
但我仍然看到冲突。我应该使用哪种包和命名空间组合?
最佳答案
原方法:
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);
关于asp.net-web-api - 无法从 'Microsoft.IdentityModel.Tokens.SymmetricSecurityKey' 转换为 'Microsoft.IdentityModel.Tokens.SigningCredentials',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41963934/