Advertisement
Guest User

Untitled

a guest
Feb 4th, 2016
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.11 KB | None | 0 0
  1. public class TokenAuthorize : AuthorizeAttribute
  2. {
  3. private const string SecurityToken = "token";
  4.  
  5. public override void OnAuthorization(AuthorizationContext filterContext)
  6. {
  7. if (Authorize(filterContext))
  8. {
  9. return;
  10. }
  11.  
  12. HandleUnauthorizedRequest(filterContext);
  13. }
  14.  
  15. private bool Authorize(AuthorizationContext actionContext)
  16. {
  17. try
  18. {
  19. HttpContextBase context = actionContext.RequestContext.HttpContext;
  20. string token = context.Request.Params[SecurityToken];
  21.  
  22. // check if the token is valid. if so, authorize action.
  23. bool isTokenAuthorized = SecurityManager.IsTokenValid(token);
  24. if (isTokenAuthorized) return true;
  25.  
  26. // if the token is not valid, check if the user is authorized by default.
  27. bool isDefaultAuthorized = AuthorizeCore(context);
  28. return isDefaultAuthorized;
  29. }
  30. catch (Exception)
  31. {
  32. return false;
  33. }
  34. }
  35. }
  36.  
  37. public class SecurityManager
  38. {
  39. private const string Alg = "HmacSHA256";
  40. private const string Salt = "rz8LuOtFBXphj9WQfvFh";
  41.  
  42. // Generates a token to be used in API calls.
  43. // The token is generated by hashing a message with a key, using HMAC SHA256.
  44. // The message is: username
  45. // The key is: password:salt
  46. public static string GenerateToken(string username, string password)
  47. {
  48. string hash = string.Join(":", new string[] { username });
  49. string hashLeft;
  50. string hashRight;
  51.  
  52. using (HMAC hmac = HMAC.Create(Alg))
  53. {
  54. hmac.Key = Encoding.UTF8.GetBytes(GetHashedPassword(password));
  55. hmac.ComputeHash(Encoding.UTF8.GetBytes(hash));
  56.  
  57. hashLeft = Convert.ToBase64String(hmac.Hash);
  58. hashRight = string.Join(":", username);
  59. }
  60.  
  61. return Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Join(":", hashLeft, hashRight)));
  62. }
  63.  
  64. // used in generating a token
  65. private static string GetHashedPassword(string password)
  66. {
  67. string key = string.Join(":", new string[] { password, Salt });
  68.  
  69. using (HMAC hmac = HMAC.Create(Alg))
  70. {
  71. // Hash the key.
  72. hmac.Key = Encoding.UTF8.GetBytes(Salt);
  73. hmac.ComputeHash(Encoding.UTF8.GetBytes(key));
  74.  
  75. return Convert.ToBase64String(hmac.Hash);
  76. }
  77. }
  78.  
  79. // Checks if a token is valid.
  80. public static bool IsTokenValid(string token)
  81. {
  82. var context = new ApplicationDbContext();
  83.  
  84. try
  85. {
  86. // Base64 decode the string, obtaining the token:username.
  87. string key = Encoding.UTF8.GetString(Convert.FromBase64String(token));
  88.  
  89. // Split the parts.
  90. string[] parts = key.Split(':');
  91. if (parts.Length != 2) return false;
  92.  
  93. // Get the username.
  94. string username = parts[1];
  95.  
  96. // Get the token for said user
  97. // var computedToken = ...
  98.  
  99. // Compare the computed token with the one supplied and ensure they match.
  100. var result = (token == computedToken);
  101.  
  102. if (!result) return false;
  103.  
  104. // get roles for user (ASP.NET Identity 2.0)
  105. var user = context.Users.Single(u => u.UserName == username);
  106. var rolesPerUser = context.UserRoles.Where(x => x.UserId == user.Id).ToList();
  107. var roles = rolesPerUser.Select(role => context.Roles.Single(r => r.Id == role.RoleId).Name);
  108. // NOTE: define public DbSet<IdentityUserRole> UserRoles { get; set; } ...
  109. // ... in your DbContext in IdentityModels.cs
  110.  
  111. HttpContext.Current.User = new GenericPrincipal(new TokenIdentity(username), roles.ToArray());
  112.  
  113. return true;
  114. }
  115. catch
  116. {
  117. return false;
  118. }
  119. }
  120. }
  121.  
  122. public class TokenIdentity : IIdentity
  123. {
  124. public string User { get; private set; }
  125.  
  126. public TokenIdentity(string user)
  127. {
  128. this.User = user;
  129. }
  130.  
  131. public string Name => User;
  132.  
  133. public string AuthenticationType => "ApplicationToken";
  134.  
  135. public bool IsAuthenticated => true;
  136. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement