.Net Core是我的新手,并且面临以下问题。
我有Authentication_API,该API返回 JWT令牌 到客户端的登录控制器。 成功登录后,我想重定向到主页,但是当我对控制器使用[Authorize]属性时,它不起作用,但是如果没有[Authorize]属性,它将显示主页。
请帮助我如何解决此问题。 我想我没有在令牌中保存令牌。
我引用了以下JWT API signal code
这是我的令牌生成器
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, user.UserId.ToString()),
new Claim(ClaimTypes.Role,user.Role.RoleNameE.ToString())
}),
Expires = DateTime.UtcNow.AddDays(7),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
此后,我想重定向到首页
这是我的“启动”页面
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// Add ASPNETCore DBContext services.
services.AddDbContext<Tejoury_MSContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DatabaseConnection")));
// configure strongly typed settings objects : abdulla
var appSettingsSection = Configuration.GetSection("AppSettings");
services.Configure<AppSettings>(appSettingsSection);
//--------------- configure jwt(JSON Web Tokens) authentication : abdulla ---------------
var appSettings = appSettingsSection.Get<AppSettings>();
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.Events = new JwtBearerEvents
{
OnTokenValidated = context =>
{
var userService = context.HttpContext.RequestServices.GetRequiredService<IUserService>();
var userId = int.Parse(context.Principal.Identity.Name);
var user = userService.GetById(userId);
if (user == null)
{
// return unauthorized if user no longer exists
context.Fail("Unauthorized");
}
return Task.CompletedTask;
}
};
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
//----------------------------------------------------------------------
// configure DI for application services : Abdulla
services.AddScoped<IUserService, UserService>();
services.AddAuthorization(options =>
{
options.AddPolicy("RequireAdminRole",
authBuilder =>
{ authBuilder.RequireRole("Admin"); });
});
}