c# - 将 JWT 从客户端发送到服务器
问题描述
我想在 ASP.NET Core 2.2 中使用 JWT 身份验证,我从 Postman 的正文和标头发送 Token,但收到 401 错误,
创建令牌的代码:
var signature = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Test API For JWT Authentication in ASP.NET Core 2.2"));
var header = new SigningCredentials(signature, SecurityAlgorithms.HmacSha256);
var payload = new JwtSecurityToken(claims: new List<Claim>
{
new Claim(ClaimTypes.Name, userInfo.Username)
} , signingCredentials:header);
var token = new JwtSecurityTokenHandler().WriteToken(payload);
return token;
startup.cs 配置:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Test API For JWT Authentication in ASP.NET Core 2.2"))
};
});
services.AddCors(options =>
{
options.AddPolicy("Cors", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.Build();
});
});
解决方案
确保您的请求是否包含authorization
具有以下值的标头Bearer access_token
:
Authentication: Bearer KJVG32532UVBU78V...
推荐阅读
- go - 如何在 goroutine 之间共享地图
- sql - 在通过 sql server 作业执行 ssis 包的运行时将运行 64 位运行时属性更改为 false
- ios - 自定义 UIView 中的无效上下文 0x0 - 后续问题
- database - 颤动的firebase数据库initState问题
- ruby - 如何在 Ruby 中将数字提高到 1/n 的幂?
- python - 使用布尔值通过 Python lxml 执行不同的 XPath 表达式
- fullcalendar - FullCalendar 在 updateEvents 后不重新渲染
- c# - C# 没有用于覆盖特定类型的可访问扩展方法
- android - 在哪里获得 Google Ads 的 gradle aar?
- python - Seaborn 条形图,条形按 y 轴排序