2017-01-12 2 views
-1

Я использую ADAL (библиотеку аутентификации Azure Directory), чтобы поговорить с API Office 365. Я понимаю, что мне нужно сохранить массив байтов от Serialize(). В памяти все работает нормально.ADAL token Persist in Database

Я пытаюсь сохранить это до varchar на SQL-сервере, который в .net C# -коде по существу является строкой.

Как я могу сохранить массив байтов в БД и прочитать его обратно. Я не знаю, какая кодировка используется для получения байтового массива. Я пробовал ASCII и, конечно, не работает. Любые эксперты?

ответ

0

Если вы хотите сохранить байты в поле varchar, вам необходимо сначала его кодировать. Например, вы можете кодировать байты в строку с использованием кодировки base64.

Однако нет необходимости кодировать байты, мы можем сохранить его в SQL, используя поле varbinary напрямую. Вот фрагмент кода, использующий базу данных для хранения токена из этого code sample:

public class ADALTokenCache : TokenCache 
{ 
     private ApplicationDbContext db = new ApplicationDbContext(); 
     string User; 
     UserTokenCache Cache; 

     // constructor 
     public ADALTokenCache(string user) 
     { 
      // associate the cache to the current user of the web app 
      User = user; 
      this.AfterAccess = AfterAccessNotification; 
      this.BeforeAccess = BeforeAccessNotification; 
      this.BeforeWrite = BeforeWriteNotification; 

      // look up the entry in the DB 
      Cache = db.UserTokenCacheList.FirstOrDefault(c => c.webUserUniqueId == User); 
      // place the entry in memory 
      this.Deserialize((Cache == null) ? null : Cache.cacheBits); 
     } 

     // clean up the DB 
     public override void Clear() 
     { 
      base.Clear(); 
      foreach (var cacheEntry in db.UserTokenCacheList) 
       db.UserTokenCacheList.Remove(cacheEntry); 
      db.SaveChanges(); 
     } 

     // Notification raised before ADAL accesses the cache. 
     // This is your chance to update the in-memory copy from the DB, if the in-memory version is stale 
     void BeforeAccessNotification(TokenCacheNotificationArgs args) 
     { 
      if (Cache == null) 
      { 
       // first time access 
       Cache = db.UserTokenCacheList.FirstOrDefault(c => c.webUserUniqueId == User); 
      } 
      else 
      { // retrieve last write from the DB 
       var status = from e in db.UserTokenCacheList 
          where (e.webUserUniqueId == User) 
          select new 
          { 
           LastWrite = e.LastWrite 
          }; 
       // if the in-memory copy is older than the persistent copy 
       if (status.First().LastWrite > Cache.LastWrite) 
       //// read from from storage, update in-memory copy 
       { 
        Cache = db.UserTokenCacheList.FirstOrDefault(c => c.webUserUniqueId == User); 
       } 
      } 
      this.Deserialize((Cache == null) ? null : Cache.cacheBits); 
     } 

     // Notification raised after ADAL accessed the cache. 
     // If the HasStateChanged flag is set, ADAL changed the content of the cache 
     void AfterAccessNotification(TokenCacheNotificationArgs args) 
     { 
      // if state changed 
      if (this.HasStateChanged) 
      { 
       Cache = new UserTokenCache 
       { 
        webUserUniqueId = User, 
        cacheBits = this.Serialize(), 
        LastWrite = DateTime.Now 
       }; 
       //// update the DB and the lastwrite     
       db.Entry(Cache).State = Cache.UserTokenCacheId == 0 ? EntityState.Added : EntityState.Modified; 
       db.SaveChanges(); 
       this.HasStateChanged = false; 
      } 
     } 

     void BeforeWriteNotification(TokenCacheNotificationArgs args) 
     { 
      // if you want to ensure that no concurrent write take place, use this notification to place a lock on the entry 
     } 
    } 
} 

public class ApplicationDbContext : DbContext 
{ 
    public ApplicationDbContext() 
     : base("DefaultConnection") 
    { 
    } 

    public DbSet<UserTokenCache> UserTokenCacheList { get; set; } 
} 

public class UserTokenCache 
{ 
    [Key] 
    public int UserTokenCacheId { get; set; } 
    public string webUserUniqueId { get; set; } 
    public byte[] cacheBits { get; set; } 
    public DateTime LastWrite { get; set; } 
}