我试图使用包System.IdentityModel.Tokens.Jwt生成令牌。我在网上找到了一些代码示例,非常简单,但后来我遇到了一个我无法弄清楚的错误。下面是我使用的代码(已为简洁起见稍作修改):尝试使用.NET JWT库生成令牌时发生错误
<%@ Application Language="C#" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Reflection" %>
<%@ Import Namespace="System.Collections" %>
<%@ Import Namespace="System.IdentityModel.Tokens" %>
<%@ Import Namespace="System.IdentityModel.Tokens.Jwt" %>
<%@ Import Namespace="System.Security.Claims" %>
<%@ Import Namespace="System.IdentityModel.Protocols.WSTrust" %>
<script runat="server">
public class TestClass
{
public static string GetJwtToken()
{
var tokenHandler = new JwtSecurityTokenHandler();
var input = "anyoldrandomtext";
var securityKey = new byte[input.Length * sizeof(char)];
Buffer.BlockCopy(input.ToCharArray(), 0, securityKey, 0, securityKey.Length);
var now = DateTime.UtcNow;
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.UserData,
"IsValid", ClaimValueTypes.String, "(local)")
}),
TokenIssuerName = "self",
AppliesToAddress = "https://www.mywebsite.com",
Lifetime = new Lifetime(now, now.AddMinutes(60)),
SigningCredentials = new SigningCredentials(new InMemorySymmetricSecurityKey(securityKey),
"http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
"http://www.w3.org/2001/04/xmlenc#sha256"),
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
return tokenString;
}
}
</script>
我不断收到以下错误在行113(VAR令牌= tokenHandler.CreateToken(tokenDescriptor);):
参数1:无法从“System.IdentityModel.Tokens.SecurityTokenDescriptor”到“Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor”
转换,但我见过很多例子在网上做的事情正是我所做的这些。我也遇到了这篇文章(https://msdn.microsoft.com/en-us/library/jj157089(v=vs.110).aspx),指出以下:
在WIF 3.5,所有的WIF类的载于 Microsoft.IdentityModel装配 (microsoft.identitymicrosoft.identitymodel.dll)。在WIF 4.5中,WIF 类已拆分为以下组件:mscorlib (mscorlib.dll),System.IdentityModel(System.IdentityModel.dll), System.IdentityModel.Services(System.IdentityModel.Services.dll)和 System.ServiceModel(System.ServiceModel.dll)。
WIF 3.5类都包含在其中一个 Microsoft.IdentityModel命名空间中;例如, Microsoft.IdentityModel,Microsoft.IdentityModel.Tokens, Microsoft.IdentityModel.Web,等等。在WIF 4.5中,WIF类 现在分布在System.IdentityModel命名空间, System.Security.Claims命名空间和System.ServiceModel.Security 命名空间中。除了这种重组之外,一些WIF 3.5类 已被放入WIF 4.5中。
我尝试了调试的缘故切换到使用Microsoft *为SecurityTokenDescriptor命名空间,然后我得到另一个一系列错误说TokenIssuerName,AppliesToAddress和寿命都没有该类有效属性。然而,当我在线查看文档时,似乎这些属性确实存在于Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor中。然而在我的Visual Studio中,当我为该类执行定义时,它们不在那里,导致我相信Visual Studio中存在某种配置问题。在我的包管理器中,它显示我已安装Microsoft.IdentityModel.Tokens v5.0.0。由于JWT库需要,我还将项目更改为.NET Framework 4.5.1。除此之外,我不知道还有什么可以看的。
终于到处去测试这个,它工作得很漂亮。非常感谢! – Rocket04