基于ASP.NET Core数据保护生成验证token示例

2025-05-29 0 72

ASP.NET Core Data Protection 不仅提供了非对称加密能力,而且提供了灵活的秘钥存储方式以及一致的加解密接口(Protect与Unprotect)。Session中用到了它,Cookie验证中用到了它,OpenIdConnect中也用到了它。。。当然你也可以在应用开发中使用它,比如这篇博文中就是用它生成激活帐户的验证token

首先在 Startup.ConfigureServices() 中注册 DataProtection 服务(注入 IDataProtectionProvider 接口的实现):

?

1

2

3

4
public void ConfigureServices(IServiceCollection services)

{

services.AddDataProtection();

}

然后在使用 DataProtection 的类的构造函数中添加 IDataProtectionProvider 接口,并用该接口创建 DataProtector ,接着以此创建 SecureDataFormat ,最后用 SecureDataFormat.Protect() 方法生成激活帐户的 token ,用 SecureDataFormat.Uprotect() 解密 token,完整的示例代码如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33
public class HomeController : Controller

{

private readonly ISecureDataFormat<string> _dataFormat;

public HomeController(IDataProtectionProvider _dataProtectionProvider)

{

var dataProtector = _dataProtectionProvider.CreateProtector(typeof(HomeController).FullName);

_dataFormat = new SecureDataFormat<string>(new StringSerializer(), dataProtector);

}

public string GenerateToken()

{

return _dataFormat.Protect(Guid.NewGuid().ToString() + ";" + DateTime.Now.AddHours(10));

}

public string DecryptToken(string token)

{

return _dataFormat.Unprotect(token);

}

private class StringSerializer : IDataSerializer<string>

{

public string Deserialize(byte[] data)

{

return Encoding.UTF8.GetString(data);

}

public byte[] Serialize(string model)

{

return Encoding.UTF8.GetBytes(model);

}

}

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

原文链接:http://www.cnblogs.com/dudu/p/6395021.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 基于ASP.NET Core数据保护生成验证token示例 https://www.kuaiidc.com/99411.html

相关文章

发表评论
暂无评论