[英]WebApi core 2.2 JWT Token not been Authorized
I was able to generate the token but if I tried to Authorize in my controller it doesn't work. 我能够生成令牌,但是如果我尝试在控制器中进行授权,它将无法正常工作。
I create a class JWT but I didn't set the issuer or audience. 我创建了一个JWT类,但没有设置发布者或受众。
private List<Claim> Claim = new List<Claim>();
public string GetUserToken(string tp,string id)
{
var sck = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")));
var sc = new SigningCredentials(sck, SecurityAlgorithms.HmacSha256Signature);
if(tp == "Host")
{
Claim.Add(new Claim(ClaimTypes.Role, "Host"));
Claim.Add(new Claim(ClaimTypes.Name, id));
}
else
{
Claim.Add(new Claim(ClaimTypes.Role, "Client"));
Claim.Add(new Claim(ClaimTypes.Name, id));
}
var token = new JwtSecurityToken(
expires: DateTime.Now.AddDays(30),
signingCredentials: sc,
claims: Claim
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
and Inside of Startup
class : 和Startup
类内部:
public void ConfigureServices(IServiceCollection services)
{
var SymmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")));
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).
AddJwtBearer(options => {
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = SymmetricSecurityKey
};
});
And in my controller I just put [Authorize(Roles ="Host")]
. 在我的控制器中,我只放置了[Authorize(Roles ="Host")]
。 Even removing the Roles
attribute still the same result, 401 Unauthorized
即使删除“ Roles
属性,结果仍然相同,即401 Unauthorized
Check your key and jwt configuration, your startup class should looks something like this: 检查您的密钥和jwt配置,您的启动类应如下所示:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
//Get the key from configuration file section
var appSettings = Configuration.GetSection("AppSettings").Get<AppSettings>();
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
//jwt configuration
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x => {
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//Configuration of cors to allow request of anothers
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
//Use the authentication service
app.UseAuthentication();
app.UseHttpsRedirection();
app.UseMvc();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.