下载依赖
Microsoft.AspNetCore.Authentication.JwtBearer
创建配置
实体类
``` namespace JWT4 { public class JWTSetting { public string SecKey { get; set; } public int ExpireSeconds { get;set; } } }
```
配置setting.json
``` { "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "JWT": { "SecKey": "1313jdfhdjf@kfdi9knfdfndnjf{}", "ExpireSeconds": 3600 } }
```
配置Program.cs
主要在如下两处添加代码:
```
using JWT4;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// JWT
builder.Services.Configure<JWTSetting>
(builder.Configuration.GetSection("JWT"));
builder.Services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(opt =>
{
var jWTSettings = builder.Configuration.GetSection("JWT").Get<JWTSetting>();
byte[] keyBytes = Encoding.UTF8.GetBytes(jWTSettings.SecKey);
SymmetricSecurityKey secKey = new SymmetricSecurityKey(keyBytes);
opt.TokenValidationParameters = new()
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = secKey
};
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication ();
app.UseAuthorization();
app.MapControllers();
app.Run();
测试
controller
创建登录方法
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace JWT4.Controllers
{
[Route("/[controller]/[action]")]
[ApiController]
public class IdentityController : ControllerBase
{
private readonly IOptionsSnapshot<JWTSetting> jwtSetting;
public IdentityController(IOptionsSnapshot<JWTSetting> jwtSetting)
{
this.jwtSetting = jwtSetting;
}
[HttpPost]
public ActionResult<string> Login(string userName,string password)
{
if(userName == "xyy123" && password == "123")
{
List<Claim> claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.NameIdentifier, userName));
claims.Add(new Claim(ClaimTypes.Role, "admin"));
string key = jwtSetting.Value.SecKey;
DateTime expire = DateTime.Now.AddDays(jwtSetting.Value.ExpireSeconds);
byte[] bytes = Encoding.UTF8.GetBytes(key);
SymmetricSecurityKey secKey = new SymmetricSecurityKey(bytes);
SigningCredentials credentials = new(secKey, SecurityAlgorithms.HmacSha256Signature);
JwtSecurityToken tokenDescriptor = new JwtSecurityToken(claims: claims, expires: expire, signingCredentials: credentials);
string jwt = new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);
return jwt;
}
else
{
return BadRequest();
}
}
}
}
只有当用户输入正确信息后,才能够登录,返回对应JWT信息
check
只有在请求中捎带验证信息,才能够执行该方法
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace JWT4.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class CheckController : ControllerBase
{
[HttpGet]
public string Test1()
{
return "ok";
}
}
}
若没有捎带信息,则:
可在Postman 中新增请求头参数:
Authorization
:Bearer
+ JWT
其他方法
获取 payload 信息
AllowAnonymous
加上后,允许不输入权限即可访问
[Authorize(Roles ="xxx")]
只有角色为 xxx 时候,才可登录
需要在创建JWT时,指定用户角色