Advertisement
Guest User

Token Authorize

a guest
Feb 2nd, 2016
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 6.61 KB | None | 0 0
  1.  public class TokenAuthAttribute : AuthorizeAttribute
  2.     {
  3.         private readonly TokenAuth tokenAuth;
  4.  
  5.         public TokenAuthAttribute()
  6.         {
  7.             this.tokenAuth = Global.ObjectFactory.GetInstance<TokenAuth>();      
  8.         }
  9.  
  10.         protected override bool IsAuthorized(HttpActionContext actionContext)
  11.         {
  12.             IEnumerable<string> tokens;
  13.             var found = actionContext.Request.Headers.TryGetValues("Token", out tokens);
  14.             if (!found)
  15.             {
  16.                 return false;
  17.             }
  18.             int userId;
  19.             var valid = this.tokenAuth.ValidateToken(tokens.FirstOrDefault(), out userId);
  20.             if (valid)
  21.             {
  22.                 actionContext.Request.Headers.Add("UserId", userId.ToString());
  23.             }
  24.             return valid;
  25.         }
  26.  
  27.         protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
  28.         {
  29.             actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
  30.                                          {
  31.                                              Content =
  32.                                                  new StringContent(
  33.                                                  "The request needs a valid token! Log in and try again.")
  34.                                          };
  35.         }
  36.     }
  37.  
  38. public class TokenAuth
  39.     {
  40.         private readonly UserDomain userDomain;
  41.  
  42.         private static readonly string StaticEncriptionPassword = "R3ally_Str0ng_PAssW0rD";
  43.  
  44.         public TokenAuth(UserDomain userDomain)
  45.         {
  46.             this.userDomain = userDomain;
  47.         }
  48.  
  49.         public bool TryGenerateToken(string email, string password, out string token)
  50.         {
  51.             token = string.Empty;
  52.             int userId;
  53.             var validLogin = this.ValidateLogin(email, password, out userId);
  54.             if (!validLogin)
  55.             {
  56.                 return false;
  57.             }
  58.  
  59.             token = this.GenerateToken(userId);
  60.             return true;
  61.         }
  62.  
  63.         public bool ValidateToken(string token, out int userId)
  64.         {
  65.             userId = -1;
  66.             token = HttpContext.Current.Server.UrlDecode(token);
  67.             if (string.IsNullOrWhiteSpace(token))
  68.             {
  69.                 return false;
  70.             }
  71.             var encriptedData = Convert.FromBase64String(token);
  72.             var data = AesDecrypt(encriptedData);
  73.             if (data.Length < 9) //invalid
  74.             {
  75.                 return false;
  76.             }
  77.             var when = DateTime.FromBinary(BitConverter.ToInt64(data, 0)); //8 bytes
  78.             userId = BitConverter.ToInt32(data, 8); //from 9th byte
  79.             return when >= DateTime.UtcNow.AddHours(-24);
  80.         }
  81.  
  82.         public string RefreshToken(int userId)
  83.         {
  84.             return this.GenerateToken(userId);
  85.         }
  86.  
  87.         private bool ValidateLogin(string email, string password, out int userId)
  88.         {
  89.             userId = -1;
  90.             var user = this.userDomain.GetUserByEmail(email);
  91.             if (user == null)
  92.             {
  93.                 return false;
  94.             }
  95.             var correctPassword = PasswordHash.ValidatePassword(password, user.PasswordHash);
  96.             if (correctPassword)
  97.             {
  98.                 userId = user.UserId;
  99.             }
  100.             return correctPassword;
  101.         }
  102.  
  103.         private string GenerateToken(int userId)
  104.         {
  105.             var time = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
  106.             var key = Guid.NewGuid().ToByteArray();
  107.             var userIdBits = BitConverter.GetBytes(userId);
  108.  
  109.             var tokenBytes = time.Concat(userIdBits).Concat(key).ToArray();
  110.             var token = Convert.ToBase64String(AesEncrypt(tokenBytes));
  111.             return HttpContext.Current.Server.UrlEncode(token);
  112.         }
  113.  
  114.         /// <summary>
  115.         /// Methods to encript byte arrays. Reference to the source: http://www.codeproject.com/Articles/769741/Csharp-AES-bits-Encryption-Library-with-Salt
  116.         /// </summary>
  117.         /// <param name="bytesToBeEncrypted"></param>
  118.         /// <returns></returns>
  119.         private static byte[] AesEncrypt(byte[] bytesToBeEncrypted)
  120.         {
  121.             byte[] encryptedBytes = null;
  122.  
  123.             // Set your salt here, change it to meet your flavor:
  124.             // The salt bytes must be at least 8 bytes.
  125.             byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
  126.  
  127.             using (var ms = new MemoryStream())
  128.             using (var aes = new RijndaelManaged())
  129.             {
  130.                 aes.KeySize = 256;
  131.                 aes.BlockSize = 128;
  132.  
  133.                 if (StaticEncriptionPassword != null)
  134.                 {
  135.                     var key = new Rfc2898DeriveBytes(StaticEncriptionPassword, saltBytes, 1000);
  136.                     aes.Key = key.GetBytes(aes.KeySize / 8);
  137.                     aes.IV = key.GetBytes(aes.BlockSize / 8);
  138.                 }
  139.  
  140.                 aes.Mode = CipherMode.CBC;
  141.  
  142.                 using (var cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
  143.                 {
  144.                     cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
  145.                     cs.Close();
  146.                 }
  147.                 encryptedBytes = ms.ToArray();
  148.             }
  149.             return encryptedBytes;
  150.         }
  151.  
  152.         private static byte[] AesDecrypt(byte[] bytesToBeDecrypted)
  153.         {
  154.             byte[] decryptedBytes = null;
  155.  
  156.             // Set your salt here, change it to meet your flavor:
  157.             // The salt bytes must be at least 8 bytes.
  158.             byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
  159.  
  160.             using (MemoryStream ms = new MemoryStream())
  161.             using (RijndaelManaged aes = new RijndaelManaged())
  162.             {
  163.                 aes.KeySize = 256;
  164.                 aes.BlockSize = 128;
  165.  
  166.                 if (StaticEncriptionPassword != null)
  167.                 {
  168.                     var key = new Rfc2898DeriveBytes(StaticEncriptionPassword, saltBytes, 1000);
  169.                     aes.Key = key.GetBytes(aes.KeySize / 8);
  170.                     aes.IV = key.GetBytes(aes.BlockSize / 8);
  171.                 }
  172.  
  173.                 aes.Mode = CipherMode.CBC;
  174.  
  175.                 using (var cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write))
  176.                 {
  177.                     cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
  178.                     cs.Close();
  179.                 }
  180.                 decryptedBytes = ms.ToArray();
  181.             }
  182.  
  183.             return decryptedBytes;
  184.         }
  185.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement