[英]Authorize attribute is not working in JWT and 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");
}
}
這是 controller 代碼,其中提到了授權屬性
[Authorize]
[EnableCors("CorsPolicy")]
[ApiController]
[Route("api/Utility")]
public class UtilityController : ControllerBase
您在Startup
class 的Configure
方法中缺少UseAuthorization
中間件。
如下所示:
app.UseAuthentication();
app.UseAuthorization(); // <-- Here it is
請注意您的TokenValidationParameters
,您的audience
是http://localhost:4200/
,與令牌聲明中的( http://localhost:4200
)不匹配:
所以只需將ValidAudience
中的TokenValidationParameters
修改為:
ValidAudience = "http://localhost:4200",
我的令牌架構是 Bearer: {'Token': 'Abcsdsdsgddcdsa'}
我將架構更改為
持有人:'Asdsaasadcaca'
它按預期工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.