一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第14天,点击查看活动详情。
前言
今天我们来讲一讲.NETcore的webApi部分的知识,重点讲解一下JWT的颁发授权toekn,这也是重点,大家一起来看看吧!
解释都在代码注释中。。。
MinimalApi支持依赖注入
1.注入上下文
2.注入服务
//Order.cs
using TestDemo;
namespace minimalAPiDemo
{
public static class Order
{
public static void search(this WebApplication app)
{
app.MapGet("add", ( string id,HttpContext context,Itest itest) =>
{
var query=context.Request.Query;
var test = itest;
return new
{
Id=id
};
}).WithTags("order");
app.MapGet("delete", () =>
{
return new
{
Id = "2"
};
}).WithTags("order");
}
}
}
//program.cs
builder.Services.AddTransient<Itest, Test>();
app.search();
63. ASP.NETCore WebApi
项目新建
项目结构解读功能支持
64. WebApi 路由
RestFull风格
特性路由--违背restful风格
【HttpGet]
[Route("GetData")] //在方法上面
【ApiController]
[Route("[controller]/[action]")]
65. Swagger配置扩展
增加版本控制功能
增加注释功能
//WeatherForecastController.cs
[ApiExplorerSettings(GroupName =nameof(ApiVison.V1))] //版本控制
/// <summary>
/// 获取
/// </summary>
/// <returns></returns>
[HttpGet(Name = "GetWeatherForecast")]
//program.cs
builder.Services.AddSwaggerGen(c =>
{
foreach (FieldInfo field in typeof(ApiVison).GetFields())
{
c.SwaggerDoc(field.Name, new Microsoft.OpenApi.Models.OpenApiInfo()
{
Title = "版本控制",
Version=field.Name,
Description=$"这是${field.Name}版本"
});
//为swagger添加注释
string basepth = Path.GetDirectoryName(typeof(Program).Assembly.Location); //获取应用程序所在目录(绝对路径)
string xmlPath = Path.Combine(basepth, "WebApiDemo.xml");
c.IncludeXmlComments(xmlPath);
}
});
//版本控制
app.UseSwaggerUI(c =>
{
foreach (FieldInfo field in typeof(ApiVison).GetFields())
{
c.SwaggerEndpoint($"/swagger/{field.Name}/swagger.json", $"{field.Name}");
}
});
Jwt授权颁发Token
Webapi鉴权授权
不支持Session/Cookies Token授权--JWT
token授权 - JWT
代码:
//AuthenticationController.cs
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using WebApiDemo.Unity;
namespace WebApiDemo.Controllers
{
[Route("api/[controller]")]
public class AuthenticationController : Controller
{private ICustomJWTService _customJWTService;
public AuthenticationController(ICustomJWTService customJWTService)
{
this._customJWTService = customJWTService;
}
[Route("Login")]
[HttpPost]
public string Login(string name,string password)
{
if("1".Equals(name) &&"111".Equals(password)){
//生成Token
string token = _customJWTService.GetToken(name,password);
return JsonConvert.SerializeObject(new
{
result=true,
token=token,
});
}
else
{
return JsonConvert.SerializeObject(new
{
result = false,
token = ""
});
}
}
}
}
//CustomHSJWTService.cs
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace WebApiDemo.Unity
{
public class CustomHSJWTService: ICustomJWTService
{
//在这里生成Token
private readonly JWTTokenOptions _JWTTokenOptions;
public CustomHSJWTService(IOptionsMonitor<JWTTokenOptions> jwtTokenOptions)
{
this._JWTTokenOptions = jwtTokenOptions.CurrentValue;
}
public string GetToken(string Username,string password)
{
//有效载荷,避免敏感信息
var claims = new[]
{
new Claim(ClaimTypes.Name,Username),
new Claim(ClaimTypes.Role,"teache()"),
new Claim("NickName",password),
};
//需要加密,需要加密key
//引入Microsoft.IdentityModel.Tokens
SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_JWTTokenOptions.SecurityKey));
SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
//Nuget引入:System.IdentityModel.Tokens.Jwt
JwtSecurityToken token = new JwtSecurityToken(
issuer: _JWTTokenOptions.Issuer,
audience: _JWTTokenOptions.Audience,
claims: claims,
expires: DateTime.Now.AddMinutes(5),//5分钟有效期
signingCredentials: creds);
string returnToken = new JwtSecurityTokenHandler().WriteToken(token);
return returnToken;
}
}
}
//ICustomJWTService.cs
namespace WebApiDemo.Unity
{
public interface ICustomJWTService
{
string GetToken(string UserName, string password);
}
}
//JWTTokenOptions.cs
namespace WebApiDemo.Unity
{
public class JWTTokenOptions
{
public string Audience
{
get;
set;
}
public string SecurityKey
{
get;
set;
}
//public SigningCredentials Credentials
//{
// get;
// set;
//}
public string Issuer
{
get;
set;
}
}
}
//program.cs
builder.Services.Configure<JWTTokenOptions>(builder.Configuration.GetSection("JWTTokenOptions"));
builder.Services.AddTransient<ICustomJWTService, CustomHSJWTService>();
//appsetting.cs
"JWTTokenOptions": {
"Audience": "http://localhost:5200",
"Issuer": "http://localhost:5200`",`
"SecurityKey": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDI2a2EJ7m872v0afyoSDJT2o1+SitIeJSWtLJU8/Wz2m7gStexajkeD+Lka6DSTy8gt9UwfgVQo6uKjVLG5Ex7PiGOODVqAEghBuS7JzIYU5RvI543nNDAPfnJsas96mSA7L/mD7RTE2drj6hf3oZjJpMPZUQI/B1Qjb5H3K3PNwIDAQAB"
}
下面是授权和鉴权的配置,在program.cs文件中:
//program.cs
//配置授权验证
//增加鉴权逻辑
JWTTokenOptions tokenOptions = new JWTTokenOptions();
builder.Configuration.Bind("JWTTokenOptions", tokenOptions);
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) //scheme
.AddJwtBearer(options=> //配置鉴权逻辑
{
options.TokenValidationParameters = new TokenValidationParameters
{
//JWT有一些默认的属性,就是给鉴权时可以筛选了
ValidateIssuer = true, //是否验证Issuer
ValidateAudience = true,//是否验证Audience
ValidateLifetime = true,//是否验证是否验证生效时间
ValidateIssuerSigningKey = true, //是否验证SecurityKey
ValidIssuer = tokenOptions.Issuer,
ValidAudience = tokenOptions.Audience,
IssuerSigningKey= new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOptions.SecurityKey)) //获取SecurityKey
};
});
//打开鉴权授权
app.UseAuthentication();
app.UseAuthorization();
总结:这是重点知识,大家认真学习,一步步来,加油!