ASP.NET Core 3.0中使用JWT认证的实现攻略如下:
- 安装必要的NuGet包
在开始之前,需要安装以下NuGet包:
- Microsoft.AspNetCore.Authentication.JwtBearer
- System.IdentityModel.Tokens.Jwt
您可以使用以下命令在命令行中安装这些NuGet包:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
dotnet add package System.IdentityModel.Tokens.Jwt
- 配置JWT认证
在Startup.cs文件中,添加以下代码以配置JWT认证:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
// ...
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.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"))
};
});
// ...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
app.UseAuthentication();
// ...
}
在上面的代码中,我们使用AddAuthentication方法添加JWT认证,并使用AddJwtBearer方法配置JWT认证选项。在TokenValidationParameters中,我们指定了JWT的验证规则,包括Issuer、Audience、Lifetime和Signing Key。
- 生成JWT Token
在需要生成JWT Token的地方,您可以使用以下代码:
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;
// ...
var claims = new[]
{
new Claim(ClaimTypes.Name, "your-name"),
new Claim(ClaimTypes.Email, "your-email"),
new Claim(ClaimTypes.Role, "your-role")
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "your-issuer",
audience: "your-audience",
claims: claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
var tokenString = new JwtSecurityTokenHandler().WriteToken(token);
在上面的代码中,我们使用JwtSecurityToken类创建JWT Token,并使用SigningCredentials类指定签名密钥和算法。在JwtSecurityToken构造函数中,我们指定了Issuer、Audience、Claims、Expires和SigningCredentials。
- 验证JWT Token
在需要验证JWT Token的地方,您可以使用以下代码:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
// ...
[Authorize]
[HttpGet]
public IActionResult Get()
{
// ...
}
在上面的代码中,我们使用Authorize属性标记需要验证JWT Token的方法。如果JWT Token验证失败,将返回401 Unauthorized响应。
以下是两个示例,演示了如何在ASP.NET Core 3.0中使用JWT认证。
示例一:使用JWT认证保护API
在这个示例中,我们将演示如何使用JWT认证保护API。
- 在Startup.cs文件中添加JWT认证配置。
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
// ...
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.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"))
};
});
// ...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
app.UseAuthentication();
// ...
}
- 在需要保护的API方法上添加Authorize属性。
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
// ...
[Authorize]
[HttpGet]
public IActionResult Get()
{
// ...
}
- 生成JWT Token。
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;
// ...
var claims = new[]
{
new Claim(ClaimTypes.Name, "your-name"),
new Claim(ClaimTypes.Email, "your-email"),
new Claim(ClaimTypes.Role, "your-role")
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "your-issuer",
audience: "your-audience",
claims: claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
var tokenString = new JwtSecurityTokenHandler().WriteToken(token);
- 在API请求中添加JWT Token。
using System.Net.Http;
using System.Net.Http.Headers;
// ...
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenString);
var response = await client.GetAsync("your-api-url");
示例二:使用JWT认证保护MVC应用程序
在这个示例中,我们将演示如何使用JWT认证保护MVC应用程序。
- 在Startup.cs文件中添加JWT认证配置。
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
// ...
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.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"))
};
});
// ...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
app.UseAuthentication();
// ...
}
- 在需要保护的MVC控制器上添加Authorize属性。
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
// ...
[Authorize]
public class HomeController : Controller
{
// ...
}
- 生成JWT Token。
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;
// ...
var claims = new[]
{
new Claim(ClaimTypes.Name, "your-name"),
new Claim(ClaimTypes.Email, "your-email"),
new Claim(ClaimTypes.Role, "your-role")
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "your-issuer",
audience: "your-audience",
claims: claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
var tokenString = new JwtSecurityTokenHandler().WriteToken(token);
- 在MVC请求中添加JWT Token。
using System.Net.Http;
using System.Net.Http.Headers;
// ...
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenString);
var response = await client.GetAsync("your-mvc-url");
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:ASP.Net Core3.0中使用JWT认证的实现 - Python技术站