asp.net core jwt demo
时间: 2023-07-28 16:29:32 浏览: 144
asp.net core jwt
4星 · 用户满意度95%
以下是一个 ASP.NET Core JWT 的示例代码,包含生成 Token 和验证 Token 的过程:
```csharp
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace JwtDemo.Controllers
{
[ApiController]
[Route("[controller]")]
public class AuthController : ControllerBase
{
private readonly IConfiguration _configuration;
public AuthController(IConfiguration configuration)
{
_configuration = configuration;
}
[AllowAnonymous]
[HttpPost("token")]
public IActionResult Token()
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, "user_id"),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString())
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
_configuration["Jwt:Issuer"],
_configuration["Jwt:Issuer"],
claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
return Ok(new
{
token = new JwtSecurityTokenHandler().WriteToken(token)
});
}
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[HttpGet("data")]
public IActionResult GetData()
{
// 返回数据
return Ok(new
{
message = "Hello, world!"
});
}
}
}
```
在上述代码中,首先我们在 `Token()` 方法中生成 JWT Token,使用 `JwtSecurityTokenHandler` 类来生成 Token,然后将其返回给客户端。在 `GetData()` 方法中使用 `[Authorize]` 特性进行身份验证,只允许授权用户访问该接口。
在 `Startup.cs` 中需要添加以下代码:
```csharp
public void ConfigureServices(IServiceCollection services)
{
// 添加 JWT 鉴权
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])),
ValidateIssuer = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidateAudience = true,
ValidAudience = Configuration["Jwt:Issuer"],
ClockSkew = TimeSpan.Zero
};
});
// 其他服务配置
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// 添加 JWT 鉴权
app.UseAuthentication();
app.UseAuthorization();
// 其他中间件配置
}
```
在 `ConfigureServices` 方法中添加 JWT 鉴权服务,使用 `AddJwtBearer` 方法添加 JWT 鉴权。在 `Configure` 方法中添加 JWT 鉴权中间件,使用 `UseAuthentication` 和 `UseAuthorization` 方法启用 JWT 鉴权。
阅读全文