【发布时间】:2021-10-09 16:07:21
【问题描述】:
我想在我的 ASP.NET MVC 网站中使用 jwt 令牌进行授权。我已经创建了一个从本教程生成 jwt 令牌的 api: https://www.c-sharpcorner.com/article/asp-net-web-api-2-creating-and-validating-jwt-json-web-token/
现在我在我的 asp.net mvc 网站中添加了以下 nuget 包:
System.IdentityModel.Tokens.Jwt 5.5.0
Microsoft.Owin.Security.Jwt 4.0.1
Microsoft.AspNet.WebApi.Owin 5.2.3
Microsoft.Owin.Host.SystemWeb 4.0.1
我还创建了一个启动文件并插入了以下代码:
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "example.com", //some string, normally web url,
ValidAudience = "example.com",
IssuerSigningKey = new
SymmetricSecurityKey(Encoding.UTF8.GetBytes("my_secret_key_12345"))
}
});
然后我使用邮递员创建一个 jwt 令牌并挑战网站的授权。 生成令牌方法如下。 (就像教程一样):
public Object GetToken()
{
string key = "my_secret_key_12345";
var issuer = "example.com"; //normally this will be your site URL
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
//Create a List of Claims, Keep claims name short
var permClaims = new List<Claim>();
permClaims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()));
permClaims.Add(new Claim("valid", "1"));
permClaims.Add(new Claim("userid", "1"));
permClaims.Add(new Claim("name", "bilal"));
//Create Security Token object by giving required parameters
var token = new JwtSecurityToken(issuer, //Issure
issuer, //Audience
permClaims,
expires: DateTime.Now.AddDays(1),
signingCredentials: credentials);
var jwt_token = new JwtSecurityTokenHandler().WriteToken(token);
return new { data = jwt_token };
}
我创建了以下方法来挑战授权:
[Authorize]
public string checkbystring()
{
return "worked";
}
但是当我在邮递员中测试时,不断弹出以下错误: IIS 10.0 详细错误 - 401.0 - 未经授权
我们将不胜感激任何关于完成这项工作的建议。
【问题讨论】:
标签: asp.net-mvc jwt