目录
一:新建WebApi项目
二:添加关键类
三:修改appsettings.json文件
四:修改Program.cs文件
五:添加控制器AuthenticationController
六:结果截图
- 右键当前解决方案、添加、新建项目。
- 点击ASP.NET Core Web API下一步。
- 输入项目名称,后缀追加.WebApi。
- 勾选使用控制器(取消选中以使用最小Api)。
- 取消勾选不使用顶级语句。
- 点击创建。
- 右键管理NuGet包引入:
- Microsoft.IdentityModel.Tokens
- Newtonsoft.Json
- System.IdentityModel.Tokens.Jwt
添加关键类JWTTokenOptions
namespace Study_ASP.NET_Core_MVC.AuthenticationCenter.Utility
{
public class JWTTokenOptions
{
public string Audience { get; set; }
public string SecurityKey { get;set; }
public string Issuer { get; set; }
}
}
添加关键类ICustomJWTService
namespace Study_ASP.NET_Core_MVC.AuthenticationCenter.Utility
{
public interface ICustomJWTService
{
string GetToken(string UserName, string PassWord);
}
}
添加关键类CustomHSJWTService
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace Study_ASP.NET_Core_MVC.AuthenticationCenter.Utility
{
public class CustomHSJWTService : ICustomJWTService
{
///
/// 注入构造函数
///
private readonly JWTTokenOptions _JWTTokenOptions;
public CustomHSJWTService(IOptionsMonitor jwtTokenOptions)
{
this._JWTTokenOptions = jwtTokenOptions.CurrentValue;
}
///
/// 用户登录成功之后
/// 用来生成Token方法
///
/// 用户账号
/// 用户密码
///
///
public string GetToken(string UserName, string PassWord)
{
//有效载荷,避免敏感信息
var claims = new[]
{
new Claim(ClaimTypes.Name,UserName),
new Claim(ClaimTypes.Role,"Administrator"),
new Claim("NickName",UserName),
new Claim("Role","Admin"),
new Claim("ABCD","ABCD"),
new Claim("Student","酱油")
};
//获取加密KEY
SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_JWTTokenOptions.SecurityKey));
//加密KEY
SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
//准备生成Token
JwtSecurityToken token = new JwtSecurityToken(issuer: _JWTTokenOptions.Issuer, audience: _JWTTokenOptions.Audience, claims: claims, expires: DateTime.Now.AddMinutes(5), signingCredentials: creds);
string returnToken = new JwtSecurityTokenHandler().WriteToken(token);
return returnToken;
}
}
}
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"JWTTokenOptions": {
"Audience": "http://localhost:5200",
"Issuer": "http://localhost:5200",
"SecurityKey": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDI2a2EJ7m872v0afyoSDJT2o1+SitIeJSWtLJU8/Wz2m7gStexajkeD+Lka6DSTy8gt9UwfgVQo6uKjVLG5Ex7PiGOODVqAEghBuS7JzIYU5RvI543nNDAPfnJsas96mSA7L/mD7RTE2drj6hf3oZjJpMPZUQI/B1Qjb5H3K3PNwIDAQAB"
}
}
using Study_ASP.NET_Core_MVC.AuthenticationCenter.Utility;
//表示整个应用程序,调用CreateBuilder方法创建一个WebApplicationBuilder对象
var builder = WebApplication.CreateBuilder(args);
//向管道容器添加注册中间件
//添加注册Controller中间件
//添加注册Swagger中间件
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
//添加注册JWT鉴权授权
builder.Services.Configure(builder.Configuration.GetSection("JWTTokenOptions"));
builder.Services.AddTransient();
//配置管道容器中间件,构造WebApplication实例
var app = builder.Build();
//配置HTTP请求管道判断开发者模式
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
//向管道添加用于将HTTP请求重定向到HTTPS的中间件
app.UseHttpsRedirection();
//向管道添加用于身份鉴权授权中间件
app.UseAuthorization();
//向管道添加用于Controller中间件
app.MapControllers();
//向管道添加启动应用程序中间件
app.Run();
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Study_ASP.NET_Core_MVC.AuthenticationCenter.Utility;
namespace Study_ASP.NET_Core_MVC.AuthenticationCenter.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AuthenticationController : Controller
{
///
/// 构造函数注入
///
private ICustomJWTService _iJWTService = null;
public AuthenticationController(ICustomJWTService customJWTService)
{
_iJWTService = customJWTService;
}
[Route("Get")]
[HttpGet]
public IEnumerable Get()
{
return new List() { 1, 2, 3, 4, 6, 7 };
}
[Route("Login")]
[HttpPost]
public string Login(string UserName, string PassWord)
{
//判断用户账号和密码
if ("VinCente".Equals(UserName) && "123456".Equals(PassWord))
{
//生成Token
string token = this._iJWTService.GetToken(UserName, PassWord);
return JsonConvert.SerializeObject(new
{
result = true,
token
});
}
else
{
return JsonConvert.SerializeObject(new
{
result = false,
token = ""
});
}
}
}
}