Guest User

AuthMiddleWare

a guest
Mar 30th, 2019
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. public class AuthenticationMiddleware
  2. {
  3. private readonly RequestDelegate _next;
  4.  
  5. public AuthenticationMiddleware(RequestDelegate next)
  6. {
  7. _next = next;
  8. }
  9.  
  10. public async Task Invoke(HttpContext context)
  11. {
  12. string authHeader = context.Request.Headers["Authorization"];
  13. if (authHeader != null && authHeader.StartsWith("Basic"))
  14. {
  15. //Extract credentials
  16. string encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
  17. Encoding encoding = Encoding.GetEncoding("iso-8859-1");
  18. string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));
  19.  
  20. int seperatorIndex = usernamePassword.IndexOf(':');
  21.  
  22. var username = usernamePassword.Substring(0, seperatorIndex);
  23. var password = usernamePassword.Substring(seperatorIndex + 1);
  24.  
  25. if (username == "user" && password == "hellofreshgoapi")
  26. {
  27. await _next.Invoke(context);
  28. }
  29. else
  30. {
  31. context.Response.StatusCode = 401; //Unauthorized
  32. return;
  33. }
  34. }
  35. else
  36. {
  37. // no authorization header
  38. context.Response.StatusCode = 401; //Unauthorized
  39. return;
  40. }
  41. }
  42. }
Add Comment
Please, Sign In to add comment