目录
一:引用Microsoft.AspNetCore.Authentication.JwtBearer
一:引用Microsoft.AspNetCore.Authentication.JwtBearer
当前项目右键管理NuGet包。
搜索Microsoft.AspNetCore.Authentication.JwtBearer,选择6.0版本的进行安装。
搜索Microsoft.AspNetCore.Authorization进行安装。
二:添加JWTTokenOptions类
namespace Study_ASP.NET_Core_MVC.WebApi.Utility
{
public class JWTTokenOptions
{
public string Audience { get; set; }
public string SecurityKey { get; set; }
public string Issuer { get; set; }
}
}
三:修改Program.cs文件
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Study_ASP.Net_Core_MVC.Services;
using Study_ASP.NET_Core_MVC.Interfaces;
using Study_ASP.NET_Core_MVC.MinimalApi;
using Study_ASP.NET_Core_MVC.MinimalApi.Utility;
using System.Text;
//表示整个应用程序,调用CreateBuilder方法创建一个WebApplicationBuilder对象
var builder = WebApplication.CreateBuilder(args);
//向管道容器添加注册中间件
//添加注册Swagger中间件
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
//配置JWT鉴权
JWTTokenOptions tokenOptions = new JWTTokenOptions();
builder.Configuration.Bind("JWTTokenOptions", tokenOptions);
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
//JWT默认属性
//是否验证Issuer
ValidateIssuer = true,
//是否验证Audience
ValidateAudience = true,
//似乎否验证失效时间
ValidateLifetime = true,
//是否验证SecurityKey
ValidateIssuerSigningKey = true,
//与签发JWT设置一致
ValidAudience = tokenOptions.Audience,
//与签发JWT设置一致
ValidIssuer = tokenOptions.Issuer,
//获取SecurityKey
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOptions.SecurityKey))
};
});
//配置JWT授权
builder.Services.AddAuthorization();
//注册Interfaces服务中间件
builder.Services.AddTransient<IPhone, ApplePhone>();
//初始化管道
var app = builder.Build();
//配置HTTP请求管道判断开发者模式
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
//向管道添加用于将HTTP请求重定向到HTTPS的中间件
app.UseHttpsRedirection();
//向管道添加用于身份鉴权授权中间件
app.UseAuthentication();
app.UseAuthorization();
//注册OrderMinimalApi中间件
app.OrderMinimalApiExtension();
//注册ProductMinimalApi中间件
app.ProductMinimalApiExtension();
//向管道添加启动应用程序中间件
app.Run();
四:配置appsettings.json文件
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"JWTTokenOptions": {
"Audience": "http://localhost:5200",
"Issuer": "http://localhost:5200",
"SecurityKey": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDI2a2EJ7m872v0afyoSDJT2o1+SitIeJSWtLJU8/Wz2m7gStexajkeD+Lka6DSTy8gt9UwfgVQo6uKjVLG5Ex7PiGOODVqAEghBuS7JzIYU5RvI543nNDAPfnJsas96mSA7L/mD7RTE2drj6hf3oZjJpMPZUQI/B1Qjb5H3K3PNwIDAQAB"
}
}
五:扩展IAuthorizeDate
using Microsoft.AspNetCore.Authorization;
namespace Study_ASP.NET_Core_MVC.MinimalApi.Utility
{
public class CustomAuthorizeData: IAuthorizeData
{
public string? Policy { get; set; }
public string? Roles { get; set; }
public string? AuthenticationSchemes { get; set; }
}
}
六:修改OrderMinimalApi
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Study_ASP.NET_Core_MVC.Interfaces;
using Study_ASP.NET_Core_MVC.MinimalApi.Utility;
namespace Study_ASP.NET_Core_MVC.MinimalApi
{
public static class OrderMinimalApi
{
public static void OrderMinimalApiExtension(this WebApplication app)
{
//向管道添加MapGet请求数据中间件返回新数据
//上下文注入、参数注入、Service服务注入
app.MapGet("/CreateOrder", (HttpContext context, int Id, IPhone iPhone) =>
{
//获取上下文
var QueryText = context.Request.Query;
//获取参数
var OrderId = Id;
//获取Service服务
var iPhone1 = iPhone;
//返回数据
return new
{
Id = 123,
Name = "VinCente",
Age = 28
};
}).WithTags("Order").RequireAuthorization(new CustomAuthorizeData()
{
AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme
});
//向管道添加MapPost请求数据中间件返回新增操作成功
app.MapPost("/AddOrder", () =>
{
return new
{
Success = true,
Message = "新增操作成功"
};
}).WithTags("Order");
//向管道添加MapPut请求数据中间件返回修改操作成功
app.MapPut("/UpdateOrder", () =>
{
return new
{
Success = true,
Message = "修改操作成功"
};
}).WithTags("Order");
//向管道添加MapDelete请求数据中间件返回删除操作成功
app.MapDelete("/DeleteOrder", () =>
{
return new
{
Success = true,
Message = "删除操作成功"
};
}).WithTags("Order");
}
}
}