在ASP.NET Core Web应用程序中,JWT(JSON Web Token)是一种常见的身份验证和授权机制。下面是一个简单的示例,演示如何在ASP.NET Core中使用JWT令牌进行身份验证和授权。
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = "your-issuer-name", ValidAudience = "your-audience-name", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key")), }; });
app.UseAuthentication();
[Authorize] [Route("api/[controller]")] public class MyController : Controller { // ... }
以上是使用ASP.NET Core JWT Token进行身份验证和授权的示例。使用此方法可以轻松地保护您的Web应用程序,并防止未经授权的访问。