我在搞(https://github.com/AjuPrince/Aju.Carefree)这个开源项目的时候,想作一些防止恶意攻击的小功能(若是 我经过页面 /Dome/GetData?id=123,那是否是不安全呢?是的,我彻底能够尝试着给id赋值后去获取数据)怎么办呢?在.Net Core 中又给如何处理呢?git
一、尝试着在.Net Core 的内部扩展方法中发现github
咱们都知道在 .Net Core 中注册服务,都是在 Startup->ConfigureServices 这个方式中 经过 services.AddXXXX 来添加的,我也尝试着看看 .Net Core 有无内置的数据保护组件,就利用 VS的智能提示功能 输入 server.Add 一个个去看,结果就被我我发现了(开心地像个孩子 哈哈)安全
F12 进去后ide
经过它的注释(Extension methods for setting up data protection services in an Microsoft.Extensions.DependencyInjection.IServiceCollection.)(译成中文:在Microsoft.Extensions.DependencyInjection.IServiceCollection设置数据保护服务的扩展方法)。学习
好,既然找到了,那咱们就来学习下它(咱们该如何使用它)。加密
二、学习、使用spa
既然知道了(.Net Core 内置了数据保护组件),那我也就在类试图中去找它了,最终仍是被我给找见了。(好不废话了)3d
咱们经过上图能够知道 .Net Core 内置了一个 IDataProtectionProvider 接口 和 IDataProtector 接口,其中 IDataProtectionProvider 接口是建立保护组件的接口,IDataProtector 是数据保护的接口,咱们能够实现这两个接口,建立数据保护组件。code
(确定有人问我,我怎么知道的)server
一样的方法,能够去看看,另外一个接口。
下面就让咱们来使用它。
1)、新建一个类
public class DataDemoViewModel { public int Id { get; set; } public string Name { get; set; } public DataDemoViewModel(int id, string name) { Id = id; Name = name; } }
2)、建立模拟数据
public class DemoController : Controller { private List<DataDemoViewModel> _listDataProtect = new List<DataDemoViewModel>(); public DemoController(){
//建立模拟数据 for (int i = 0; i < 6; i++) { _listDataProtect.Add(new DataDemoViewModel(i, "Aju_Carefree" + i)); } } }
3)、在Startup类的ConfigureService方法中添加服务
services.AddDataProtection();
4)、在DemoController中 DI注入
public class DemoController : Controller { private List<DataDemoViewModel> _listDataProtect = new List<DataDemoViewModel>(); private readonly IDataProtector _dataProtector; public DemoController(IDataProtectionProvider dataProtectionProvider) { //建立模拟数据 for (int i = 0; i < 6; i++) { _listDataProtect.Add(new DataDemoViewModel(i, "Aju_Carefree" + i)); } _dataProtector = dataProtectionProvider.CreateProtector("aju_carefree_string"); } }
5)、使用
#region 数据保护组件Demo public IActionResult ProtectIndex() { var outputModel = _listDataProtect.Select(item => new {
//使用 IDataProtector 接口的 Protect 方法对id字段进行加密 Id = _dataProtector.Protect(item.Id.ToString()), item.Name }); return Ok(outputModel); } public IActionResult GetProtect(string id) {
//使用 IDataProtector 接口的 Unprotect 方法对id字段进行解密 var orignalId = int.Parse(_dataProtector.Unprotect(id)); var outputModel = _listDataProtect.Where(s => s.Id == orignalId); return Ok(outputModel); } #endregion
6)结果展现
(1)请求 /Demo/ProtectIndex
刷新页面,id 值是变的。
(2)、请求 /Home/GetProtect?id=(id取了上图中的第一个(框框圈的))
说明:
(1):使用Provider建立Protector 的时候,咱们传入了一个参数“aju_carefree_string”,这个参数标明了这个保护器的用途,也能够看成这个保护器的名字。(不一样用途的保护器,不能解密对方方加密的数据)
(2):还有一个类型的数据保护组件(ITimeLimitedDataProtector(带过时时间的数据保护器))就不在这里作说明了,用法差很少。
(3):本篇文章,只是对数据保护组件的抛砖引玉(不仅是说 它的用法就只能这么用,彻底能够有别的用法。)
(4):本文的代码所有上传至Github(https://github.com/AjuPrince/Aju.Carefree)(DemoController )
参考文章:
若是以为写的还不错的话,就点个推荐呗! 哈哈
下一篇 需求了解些什么呢?留言哦!(我会从留言最多中选择一个内容来分享 个人见解及使用(固然前提是我会哦 哈哈))
本人有意组建兰州线下.Net 开发社区,有意者加群(QQ:649708779)若是条件容许的话,将会在8月中旬,组织个活动(只是有这个想法)