You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
1.7 KiB

1 year ago
  1. using log4net;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Net.Http;
  6. using System.Web;
  7. namespace JsonRx.Helper
  8. {
  9. public static class HttpRequestMessageExtensions
  10. {
  11. private const string HttpContext = "MS_HttpContext";
  12. private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";
  13. public static string GetClientIpAddress(this HttpRequestMessage request)
  14. {
  15. if (request == null)
  16. return string.Empty;
  17. if (request.Properties.ContainsKey(HttpContext))
  18. {
  19. dynamic ctx = request.Properties[HttpContext];
  20. if (ctx != null)
  21. {
  22. return ctx.Request.UserHostAddress;
  23. }
  24. }
  25. if (request.Properties.ContainsKey(RemoteEndpointMessage))
  26. {
  27. dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage];
  28. if (remoteEndpoint != null)
  29. {
  30. return remoteEndpoint.Address;
  31. }
  32. }
  33. return null;
  34. }
  35. private static readonly ILog Log = LogManager.GetLogger(typeof(HttpRequestMessageExtensions));
  36. public static string GetJWTToken(this HttpRequestMessage request)
  37. {
  38. string jwt = string.Empty;
  39. try
  40. {
  41. var id = request.Headers.GetValues("Authorization").FirstOrDefault();
  42. return id.StartsWith("Bearer") ? id.Substring(7) : id;
  43. }
  44. catch(Exception ex)
  45. {
  46. Log.Error("INVALID_JWT_TOKEN", ex);
  47. }
  48. return jwt;
  49. }
  50. }
  51. }