要使用ASP.NET Core 2.2进行身份验证,可以按照以下步骤进行操作:
创建一个新的ASP.NET Core 2.2项目。
在Startup.cs
文件中,添加using Microsoft.AspNetCore.Authentication.Cookies;
以及using Microsoft.AspNetCore.Authentication.JwtBearer;
命名空间。
在ConfigureServices
方法中,添加身份验证服务的配置:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddCookie()
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "your_issuer",
ValidAudience = "your_audience",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key"))
};
});
在上述代码中,我们添加了两种身份验证方案:CookieAuthentication和JwtBearerAuthentication。CookieAuthentication用于基于Cookie的身份验证,JwtBearerAuthentication用于基于JWT的身份验证。
Configure
方法中,添加身份验证的中间件:app.UseAuthentication();
[Authorize]
特性来限制访问:[Authorize]
public IActionResult Secret()
{
return View();
}
在视图中,您可以使用User.Identity.Name
属性来获取当前登录用户的用户名或其他声明:
Welcome, @User.Identity.Name!
这是一个基本的示例,您可以根据自己的需求进行更改和扩展。有关更详细的示例,您可以参考Microsoft的官方文档:https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-2.2