Advertisement
Guest User

Untitled

a guest
Aug 1st, 2017
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.55 KB | None | 0 0
  1. public class RestAuthorizationManager : ServiceAuthorizationManager
  2. {
  3.     private readonly string _correctUserName;
  4.     private readonly string _correctPasswordHash;
  5.  
  6.     public RestAuthorizationManager()
  7.     {
  8.         _correctUserName = ConfigurationManager.AppSettings["User"];
  9.         _correctPasswordHash = ConfigurationManager.AppSettings["PasswordHash"];
  10.     }
  11.  
  12.     protected override bool CheckAccessCore(OperationContext operationContext)
  13.     {
  14.         if (WebOperationContext.Current != null)
  15.         {
  16.             var authHeader = WebOperationContext.Current.IncomingRequest.Headers["Authorization"];
  17.             if (!string.IsNullOrEmpty(authHeader))
  18.             {
  19.                 var svcCredentials = Encoding.ASCII.GetString(Convert.FromBase64String(authHeader.Substring(6))).Split(':');
  20.                 var user = new { Name = svcCredentials[0], Password = svcCredentials[1] };
  21.  
  22.                 if (user.Name == _correctUserName && GetHash(user.Password) == _correctPasswordHash)
  23.                 {
  24.                     return true;
  25.                 }
  26.                 return false;
  27.             }
  28.         }
  29.         if (WebOperationContext.Current != null)
  30.         {
  31.             WebOperationContext.Current.OutgoingResponse.Headers.Add("WWW-Authenticate: Basic realm=\"Enter your password\"");
  32.             WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Unauthorized;
  33.             return false;
  34.         }
  35.         throw new WebFaultException(HttpStatusCode.Unauthorized);
  36.     }
  37.  
  38.     private static string GetHash(string stringToHash)
  39.     {
  40.         byte[] passwordBytes = Encoding.ASCII.GetBytes(stringToHash);
  41.         using (var sha1 = new SHA1Managed())
  42.         {
  43.             var hash = sha1.ComputeHash(passwordBytes);
  44.             return Convert.ToBase64String(hash);
  45.         }
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement