Guest User

Untitled

a guest
Jan 14th, 2018
277
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. public class BasicAuthFilter : ActionFilterAttribute
  2. {
  3. private readonly string _username;
  4. private readonly string _password;
  5. private readonly string _realm;
  6.  
  7. public BasicAuthFilter(string username, string password)
  8. {
  9. _username = username;
  10. _password = password;
  11. }
  12.  
  13. public BasicAuthFilter(string username, string password, string realm)
  14. : this(username, password)
  15. {
  16. _username = username;
  17. _password = password;
  18. _realm = realm;
  19. }
  20.  
  21. public override void OnActionExecuting(ActionExecutingContext filterContext)
  22. {
  23. if (filterContext == null)
  24. {
  25. throw new ArgumentNullException("filterContext");
  26. }
  27.  
  28. var auth = filterContext.HttpContext.Request.Headers["Authorization"];
  29.  
  30. if (!String.IsNullOrEmpty(auth))
  31. {
  32. var encodedDataAsBytes = Convert.FromBase64String(auth.Replace("Basic ", ""));
  33. var value = Encoding.ASCII.GetString(encodedDataAsBytes);
  34. var userpass = value;
  35. var user = userpass.Substring(0, userpass.IndexOf(':'));
  36. var pass = userpass.Substring(userpass.IndexOf(':') + 1);
  37.  
  38. if (user.ToLowerInvariant() != _username && pass.ToLowerInvariant() != _password)
  39. {
  40. DenyUser(filterContext);
  41. }
  42. }
  43. else
  44. {
  45. DenyUser(filterContext);
  46. }
  47. }
  48.  
  49. private void DenyUser(ControllerContext filterContext)
  50. {
  51. filterContext.HttpContext.Response.Clear();
  52. filterContext.HttpContext.Response.StatusCode = 401;
  53. filterContext.HttpContext.Response.StatusDescription = "Unauthorized";
  54. filterContext.HttpContext.Response.AddHeader("WWW-Authenticate", "Basic realm=\"" + _realm + "\"");
  55. filterContext.HttpContext.Response.End();
  56. }
Add Comment
Please, Sign In to add comment