NetCore+Dapper WebApi架构搭建(六):添加JWT认证
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架构搭建(四):仓储的依赖注入
上一节我们讲到实体,仓储接口和仓储接口的实现需要遵循约定的命名规范,不仅是规范,而且为了依赖注入,现在我们实现仓储的依赖注入 在NetCore WebApi项目中新添加一个文件夹(Unit),当然你也 ...
- NetCore+Dapper WebApi架构搭建(五):Swagger构建WebApi界面
上一节讲解了仓储的依赖注入,想必现在都可以通过构造函数依赖注入直接调用 但是WebApi只是提供一个接口调用,为了方便我们的操作,我们得给他加上一个图形化界面工具,使用Swagger WebApi项目 ...
- NetCore+Dapper WebApi架构搭建(三):添加实体和仓储
上一节讲了类库添加一些底层的基本封装,下面来添加实体和仓储 1.Entities文件夹添加一个实体类Users,继承BaseModel,即拥有BaseModel的主键 using System; na ...
- NetCore+Dapper WebApi架构搭建(一):基本框架
初衷是想用dapper搭建一个高性能的架构,因为dapper操作数据库的效率很高 1.VS创建一个NetCore WebApi的框架,然后解决方案添加一个NetStandard的类库 整个解决方案如图 ...
- NetCore+Dapper WebApi架构搭建(二):底层封装
看下我们上一节搭建的架构,现在开始从事底层的封装 1.首先需要一个实体的接口IEntity namespace Dinner.Dapper { public interface IEntity< ...
- ASP.NET Core 6.0 添加 JWT 认证和授权
序言 本文将分别介绍 Authentication(认证) 和 Authorization(授权). 并以简单的例子在 ASP.NET Core 6.0 的 WebAPI 中分别实现这两个功能. 相关 ...
- 如何简单的在 ASP.NET Core 中集成 JWT 认证?
前情提要:ASP.NET Core 使用 JWT 搭建分布式无状态身份验证系统 文章超长预警(1万字以上),不想看全部实现过程的同学可以直接跳转到末尾查看成果或者一键安装相关的 nuget 包 自上一 ...
- Asp.net Core认证和授权:JWT认证和授权
JWT验证一般用户移动端,因为它不像cookie验证那样,没有授权跳转到登陆页面 JWT是json web token的简称,在 jwt.io 网址可以看到 新建一个API项目,通过postman ...
- drf JWT认证模块与自定制
JWT模块 在djangorestframework中,有一款扩展模块可用于做JWT认证,使用如下命令进行安装: pip install djangorestframework-jwt 现在,就让我们 ...
随机推荐
- Anaconda+django写出第一个web app(五)
今天开始学习网页风格和设计,就像python有Web框架一样,也有一些CSS框架.对于CSS框架,我们可以使用默认的样式,也可以在原基础上编辑修改.本教程使用的是materialize这个CSS框架[ ...
- Python练习-一个简单易懂的迭代器,了解一下
今天我们学习了迭代器,其实可以理解为是一个元素容器被遍历的方式,不难理解,看看下面的小例子: # 编辑者:闫龙 #一个简单的迭代器 l = [1,2,3,4,5,6,7]#建立一个列表l ite = ...
- windbg分析net程序内存泄漏问题
1 问题简介 有客户反馈,打了最新补丁后,服务器的内存暴涨,一直降不下来,程序非常卡.在客户的服务器上抓了一个dump文件,开始分析. 分析问题的思路: 1.找到是那些资源占用了大量内存? ...
- 【多视图几何】TUM 课程 第2章 刚体运动
课程的 YouTube 地址为:https://www.youtube.com/playlist?list=PLTBdjV_4f-EJn6udZ34tht9EVIW7lbeo4 .视频评论区可以找到课 ...
- meterpreter使用
1.基本命令 background:将meterpreter终端隐藏在后台 sessions:查看已经成功获取的会话,想继续与某会话进行交互使用sessions –i quit:直接关闭当前meter ...
- Spring4笔记3--Bean的装配
Bean的装配: Bean 的装配,即 Bean 对象的创建.容器根据代码要求创建 Bean 对象后再传递给代码的过程,称为 Bean 的装配. 1. 创建Bean对象的方式: 1. 通过 getBe ...
- linux下的usb抓包方法【转】
转自:http://blog.chinaunix.net/uid-11848011-id-4508834.html 1.配置内核使能usb monitor: make menuconfig ...
- 使用IDEA进行打包
使用IDEA打jar包: 1.
- 洛谷P3387缩点
传送门 有向图.. 代码中有两种方法,拓扑排序和记忆化搜索 #include <iostream> #include <cstdio> #include <cstring ...
- 最后一面《HR面》------十大经典提问
1.HR:你希望通过这份工作获得什么? 1).自杀式回答:我希望自己为之工作的企业能够重视质量,而且会给做得好的员工予以奖励.我希望通过这份工作锻炼自己,提升自己的能力,能让公司更加重视我. a.“我 ...