JWT CORE6.0 教學 只有program
时间: 2023-10-09 11:04:46 浏览: 35
以下是使用JWT CORE 6.0的教程:
1. 打开Visual Studio,并创建一个新的ASP.NET Core Web应用程序。
2. 在“新项目”对话框中,选择“Web应用程序”模板,并确保选择“.NET Core”和“ASP.NET Core 6.0”作为目标框架和模板。
3. 选择“API”模板,并单击“创建”按钮。
4. 在Solution Explorer中,右键单击项目名称,并选择“Manage NuGet Packages”选项。
5. 在NuGet包管理器中搜索“Microsoft.AspNetCore.Authentication.JwtBearer”包,并安装它。
6. 在Startup.cs文件中,添加以下代码:
```csharp
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
public void ConfigureServices(IServiceCollection services)
{
var key = Encoding.ASCII.GetBytes("your-secret-key"); // 替换成你自己的密钥
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, IWebHostEnvironment env)
{
// ...
app.UseAuthentication();
app.UseAuthorization();
// ...
}
```
7. 在Controller中,添加以下代码:
```csharp
using System.Collections.Generic;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("[controller]")]
public class SampleController : ControllerBase
{
[HttpGet]
[Authorize]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
```
这将启用JWT身份验证,并要求在访问`/sample`端点时提供有效的JWT令牌。如果没有令牌,则会返回401未授权响应。