1:引用需要的程序集 :System.IdentityModel.Token.JWT
2:创建一个新的控制器,用于授权功能
using Demo.APIDbcontext;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Cors;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace Demo.Controllers
{
[Route("api/[controller]/[Action]")]
[ApiController]
public class JWT : ControllerBase
{
private readonly IConfiguration _configuration; //注入钥匙
private readonly BloggingContext _context; //EF框架注入依赖
public JWT(BloggingContext context, IConfiguration configuration)
{
_context = context;
_configuration = configuration;
}
[HttpPost]
public IActionResult Login(string username, string pwd)
{
//var writerInfo = _context.Users.Find(username);
//使用EF与数据库交互获取用户信息
//验证密码
if (username == "1")
//writerInfo != null && writerInfo.pwd == int.Parse(pwd) 验证数据库内的密码
{
//登录成功
//header
var signingAlgorithm = SecurityAlgorithms.HmacSha256;
//payload
var claims = new Claim[] {
new Claim(JwtRegisteredClaimNames.Sub,"qq"),
new Claim("Id","1"),
new Claim("UserName","admin")
//qq 1 admin为模拟信息,实际情况通过前面的EF框架查询数据库信息后插入
};
//signiture
var secretByte = Encoding.UTF8.GetBytes(_configuration["Authentication:SecretKey"]);
var signingKey = new SymmetricSecurityKey(secretByte);
var signingCredentials = new SigningCredentials(signingKey, signingAlgorithm);
var token = new JwtSecurityToken(
issuer: "xiechengwang",//谁发布 输入网址或者localhost:这类
audience: "xiechengwang",//发布给谁 输入网址或者localhost:这类
claims: claims,
notBefore: DateTime.Now,
expires: DateTime.Now.AddDays(1),
signingCredentials //字符串签名
);
var tokenStr = new JwtSecurityTokenHandler().WriteToken(token);
return Ok(tokenStr);
}
else
{
return BadRequest();
}
}
}
}
3:服务中进行注册
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(option =>
{
option.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SDMC-CJAS1-SAD-DFSFA-SADHJVF-VF")),
//SDMC-CJAS1-SAD-DFSFA-SADHJVF-VF为密钥
ValidateIssuer = true,
ValidIssuer = "xiechengwang",
ValidateAudience = true,
ValidAudience = "xiechengwang",
ValidateLifetime = true,
ClockSkew = TimeSpan.FromDays(1)
};
});
4:启动鉴权授权
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthentication();//鉴权
app.UseAuthorization();//授权
app.MapControllers();
app.Run();
5:在需要的鉴权授权的API 中调用文章来源:https://www.toymoban.com/news/detail-622450.html
[Authorize]//需要
[AllowAnonymous]//不需要
[HttpGet]
public Users? GetUsers()
{
}
6:发送请求接口时候 请求头 {Authorzation:"bearer"+空格 + token}文章来源地址https://www.toymoban.com/news/detail-622450.html
到了这里,关于.NET WebAPI 运用JWT鉴权授权的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!