1.安装jwt包
2.配置appsetting.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
//练习方便,没从数据库读取用户信息,登陆的时候用户信息从这里取
"ApiUser": {
"UserName": "admin",
"UserPassword": "123456"
},
//JWT配置信息(也可以不在这里定义,直接在方法中定义)
"JWT": {
"SecretKey": "assdfghkldsf@123!", //密钥
"Issuer": "2222", //发行人
"Expires": 10, //发行时间和到期时间间隔10分钟
"Audience": "22333" //受众
}
}
3.启用jwt服务
using Gremlin.Net.Driver.Messages;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using System.Text;
using WebApiTest1.Controllers;
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.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidIssuer = builder.Configuration["JWT:Issuer"],
ValidateAudience = true,
ValidAudience = builder.Configuration["JWT:Audience"],
ValidateLifetime = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JWT:SecretKey"]))
};
options.Events = new JwtBearerEvents
{
OnChallenge = context =>
{
//此处代码为终止.Net Core默认的返回类型和数据结果,这个很重要哦,必须
context.HandleResponse();
//自定义自己想要返回的结果
var payload = JsonConvert.SerializeObject(new ResponseResult(){ code = 401,
success = false,
msg = "权限验证失败!"
});
//自定义返回的数据类型
context.Response.ContentType = "application/json";
//自定义返回状态码,默认为401 我这里改成 200
context.Response.StatusCode = StatusCodes.Status200OK;
//context.Response.StatusCode = StatusCodes.Status401Unauthorized;
//输出Json数据结果
context.Response.WriteAsync(payload);
return Task.FromResult(0);
}
};
}
);
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
4.实现生成token接口
using Intercom.Core;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using System.Text;
namespace WebApiTest1.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet("[action]")]
public ResponseResult Login(string userName, string userPassword)
{
try
{
ResponseResult result = new ResponseResult();
// 读取appsetting.json文件
var configurationRoot = new ConfigurationBuilder()
.SetBasePath(Path.Combine(Directory.GetCurrentDirectory()))
.AddJsonFile("appsettings.json", optional: false)
.Build();
if (userName == configurationRoot.GetSection("ApiUser:UserName").Value && userPassword == configurationRoot.GetSection("ApiUser:UserPassword").Value)
{
// 1. 定义需要使用到的Claims
// claim就是声明,就像身份证上的地址,个人信息
var claims = new[]
{
new Claim("Id", "9527"),
new Claim("Name", "Admin")
};
// 2. 从 appsettings.json 中读取SecretKey
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configurationRoot.GetSection("JWT:SecretKey").Value));
// 3. 选择加密算法
var algorithm = SecurityAlgorithms.HmacSha256;
// 4. 生成Credentials
var signingCredentials = new SigningCredentials(secretKey, algorithm);
// 5. 从 appsettings.json 中读取Expires
var expires = Convert.ToDouble(configurationRoot.GetSection("JWT:Expires").Value);
// 6. 根据以上,生成token
var token = new JwtSecurityToken(
configurationRoot.GetSection("JWT:Issuer").Value, //Issuer
configurationRoot.GetSection("JWT:Audience").Value, //Audience
claims, //Claims,
DateTime.Now, //notBefore
DateTime.Now.AddMinutes(expires), //expires 令牌过期时间
signingCredentials //Credentials
);
// 7. 将token变为string
var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
result.data = jwtToken;
result.success = true;
result.msg = "认证成功!";
_userProfile = GetModel(userName);
}
else
{
result.success = false;
result.msg = "用户名或密码错误!";
}
return result;
}
catch (Exception e)
{
string error = JsonConvert.SerializeObject(e);
throw;
}
}
public class ResponseResult
{
public int code { get; set; }
public bool success { get; set; }
public string msg { get; set; }
public string data { get; set; }
}
}