NetCore+Dapper WebApi架构搭建(六):添加JWT认证

2022-11-18,,,,

WebApi必须保证安全,现在来添加JWT认证

1、打开appsettings.json添加JWT认证的配置信息

2、在项目根目录下新建一个Models文件夹,添加一个JwtSettings.cs的实体

 namespace Dinner.WebApi.Models
{
public class JwtSettings
{
/// <summary>
/// 证书颁发者
/// </summary>
public string Issuer { get; set; } /// <summary>
/// 允许使用的角色
/// </summary>
public string Audience { get; set; } /// <summary>
/// 加密字符串
/// </summary>
public string SecretKey { get; set; }
}
}

3、Startup.cs文件中的ConfigureServices添加Jwt认证的代码

 #region JWT认证

             services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings"));
JwtSettings setting = new JwtSettings();
//绑定配置文件信息到实体
Configuration.Bind("JwtSettings", setting);
//添加Jwt认证
services.AddAuthentication(option =>
{
option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(config =>
{
config.TokenValidationParameters = new TokenValidationParameters
{
ValidAudience = setting.Audience,
ValidIssuer = setting.Issuer,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(setting.SecretKey))
};
/*
config.SecurityTokenValidators.Clear();
config.SecurityTokenValidators.Add(new MyTokenValidate());
config.Events = new JwtBearerEvents()
{
OnMessageReceived = context =>
{
var token = context.Request.Headers["myToken"];
context.Token = token.FirstOrDefault();
return Task.CompletedTask;
}
};
*/
}); #endregion

4、Startup.cs文件中的Configure添加Jwt认证的代码

 app.UseAuthentication();

5、基本配置都弄完了,现在是生成JwtToken,在ValuesController中添加一个生成Jwt的Action

 using Dinner.WebApi.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text; namespace Dinner.WebApi.Controllers
{
[Route("api/[controller]/[action]")]
public class ValuesController : Controller
{
private readonly JwtSettings setting;
public ValuesController(IOptions<JwtSettings> _setting)
{
setting = _setting.Value;
}
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
} // GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
} // POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
} // PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
} // DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
} [HttpGet]
public IActionResult GetGenerateJWT()
{
try
{
var claims = new Claim[]
{
new Claim(ClaimTypes.Name, "wangshibang"),
new Claim(ClaimTypes.Role, "admin, Manage")
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(setting.SecretKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
setting.Issuer,
setting.Audience,
claims,
DateTime.Now,
DateTime.Now.AddMinutes(),
creds);
return Ok(new { Token = new JwtSecurityTokenHandler().WriteToken(token) });
}
catch (Exception ex)
{
return BadRequest(ex.Message);
} }
}
}

这样调用这个方法就会生成一个JwtToken,然后在UsersController上面添加一个[Authorize]的特性

上一篇我们说过SwaggerUI配置的最后一句有一个options.OperationFilter<HttpHeaderOperation>(); 这里我们来看这个HttpHeaderOperation

 using Microsoft.AspNetCore.Authorization;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Collections.Generic;
using System.Linq; namespace Dinner.WebApi
{
public class HttpHeaderOperation : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
if (operation.Parameters == null)
{
operation.Parameters = new List<IParameter>();
} var actionAttrs = context.ApiDescription.ActionAttributes(); var isAuthorized = actionAttrs.Any(a => a.GetType() == typeof(AuthorizeAttribute)); if (isAuthorized == false) //提供action都没有权限特性标记,检查控制器有没有
{
var controllerAttrs = context.ApiDescription.ControllerAttributes(); isAuthorized = controllerAttrs.Any(a => a.GetType() == typeof(AuthorizeAttribute));
} var isAllowAnonymous = actionAttrs.Any(a => a.GetType() == typeof(AllowAnonymousAttribute)); if (isAuthorized && isAllowAnonymous == false)
{
operation.Parameters.Add(new NonBodyParameter()
{
Name = "Authorization", //添加Authorization头部参数
In = "header",
Type = "string",
Required = false
});
}
}
}
}

这个代码主要就是在swagger页面添加了一个Authorization的头部输入框信息,以便来进行验证

现在我们基本工作都做好了,打开页面测试吧,注意:传入的Authorization参数必须是Bearer xxxxxxx的形式(xxxxxxx为生成的Token)

他返回了Http200就是成功了

整个项目的框架基本算是搭建好了,这只是一个雏形而已,其实Authorize这一块需要建一个BaseController继承Controller再在BaseController上添加一个Authorize然后所有Controller继承BaseController就不用一个一个的写Authorize了,不需要验证的加个AllowAnonymous就可以了,其他的直接扩展仓储接口写仓储就可以直接调用了

源码地址: https://github.com/wangyulong0505/Dinner

NetCore+Dapper WebApi架构搭建(六):添加JWT认证的相关教程结束。

《NetCore+Dapper WebApi架构搭建(六):添加JWT认证.doc》

下载本文的Word格式文档,以方便收藏与打印。