首頁  >  文章  >  後端開發  >  ASP.NET Core資料保護產生驗證token

ASP.NET Core資料保護產生驗證token

高洛峰
高洛峰原創
2017-02-27 16:34:162434瀏覽

ASP.NET Core Data Protection 不僅提供了非對稱加密能力,而且提供了靈活的秘鑰儲存方式以及一致的加解密介面(Protect與Unprotect)。 Session中用到了它,Cookie驗證中用到了它,OpenIdConnect中也用到了它。 。 。當然你也可以在應用程式開發中使用它,像是這篇文章中就是用它產生啟動帳號的驗證token。

首先在Startup.ConfigureServices() 中註冊DataProtection 服務(注入IDataProtectionProvider 介面的實作):

##

public void ConfigureServices(IServiceCollection services)
{
  services.AddDataProtection();
}

#然後使用DataProtection 的類別的建構函式中加入IDataProtectionProvider 接口,並用該介面建立DataProtector ,接著以此建立SecureDataFormat ,最後用SecureDataFormat.Protect() 方法產生啟動帳號的token ,用SecureDataFormat.Uprotect() 解密token,完整的範例程式碼如下:

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);
    }
  }
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持PHP中文網。

更多ASP.NET Core資料保護產生驗證token相關文章請關注PHP中文網!


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn