c# - 授权属性在 JWT 和 asp.net core 2.1 中不起作用
问题描述
我已经为 .net 核心客户端实现了 JWT,但是当我放置授权属性时,它每次都会给我 401 未经授权的响应。我尝试在中间件的属性中提到模式名称。更改序列。通过堆栈溢出的大量链接。
下面是startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerDocumentation();
services.ConfigureCors();
services.ConfigureIISIntegration();
services.ConfigureLoggerService();
services.ConfigureSqlContext(Configuration);
services.ConfigureRepositoryWrapper();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "http://localhost:5000",
ValidAudience = "http://localhost:4200/",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSecretKey@345"))
};
});
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerManager logger)
{
app.UseSwaggerDocumentation();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpStatusCodeExceptionMiddleware();
app.UseCors("CorsPolicy");
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.All
});
app.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == 404
&& !Path.HasExtension(context.Request.Path.Value))
{
context.Request.Path = "/index.html";
await next();
}
});
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc();
}
下面是 JWT 初始化的代码
if (userInfo.Any(c => c.ValidUser == "Y"))
{
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSecretKey@345"));
var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, vsecGetPasswordByUserName.LoginId),
new Claim(ClaimTypes.Role, "Admin")
};
var tokeOptions = new JwtSecurityToken(
issuer: "http://localhost:5000",
audience: "http://localhost:4200",
claims: claims,
expires: DateTime.Now.AddMinutes(5),
signingCredentials: signinCredentials
);
var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions);
return Ok(new { UserInfo = userInfo, TokenString = tokenString });
}
else
{
throw new HttpStatusCodeException(StatusCodes.Status401Unauthorized, @"User not valid");
}
}
这是提到授权属性的控制器代码
[Authorize]
[EnableCors("CorsPolicy")]
[ApiController]
[Route("api/Utility")]
public class UtilityController : ControllerBase
解决方案
请注意 your TokenValidationParameters
, your audience
is ,它与令牌声明http://localhost:4200/
中的 one( ) 不匹配:http://localhost:4200
所以只需将ValidAudience
in修改TokenValidationParameters
为:
ValidAudience = "http://localhost:4200",
推荐阅读
- server - OroCRM 让我的托管服务器变慢?
- css - 如何获得适合视口的垂直线?
- python - 带有 alpha 交互的 matplotlib 图例
- python - 如何在 Django 中表达一对多并使用附加和删除?
- php - 覆盖表名后创建不起作用
- ajax - 如何允许formData发送null
- python - boto 3 中 Comprehend 的“DataAccessRoleArn”是什么?
- dynamics-crm - Dynamics 365 FetchXML - 对字符串使用 IN 运算符
- identityserver4 - Identity Server 4 是否符合 NIST 标准?
- rest - 如何在 REST::Client perl 中进行不安全的 SSL 连接