2
0

HttpListenerContext.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Net;
  3. using System.Security.Principal;
  4. using System.Threading.Tasks;
  5. using SocketHttpListener.Net.WebSockets;
  6. namespace SocketHttpListener.Net
  7. {
  8. public sealed unsafe partial class HttpListenerContext
  9. {
  10. private HttpListenerResponse _response;
  11. private IPrincipal _user;
  12. public HttpListenerRequest Request { get; }
  13. public IPrincipal User => _user;
  14. // This can be used to cache the results of HttpListener.AuthenticationSchemeSelectorDelegate.
  15. internal AuthenticationSchemes AuthenticationSchemes { get; set; }
  16. public HttpListenerResponse Response => _response;
  17. public Task<HttpListenerWebSocketContext> AcceptWebSocketAsync(string subProtocol)
  18. {
  19. return AcceptWebSocketAsync(subProtocol, HttpWebSocket.DefaultReceiveBufferSize, WebSocket.DefaultKeepAliveInterval);
  20. }
  21. public Task<HttpListenerWebSocketContext> AcceptWebSocketAsync(string subProtocol, TimeSpan keepAliveInterval)
  22. {
  23. return AcceptWebSocketAsync(subProtocol, HttpWebSocket.DefaultReceiveBufferSize, keepAliveInterval);
  24. }
  25. }
  26. public class GenericPrincipal : IPrincipal
  27. {
  28. private IIdentity m_identity;
  29. private string[] m_roles;
  30. public GenericPrincipal(IIdentity identity, string[] roles)
  31. {
  32. if (identity == null)
  33. throw new ArgumentNullException(nameof(identity));
  34. m_identity = identity;
  35. if (roles != null)
  36. {
  37. m_roles = new string[roles.Length];
  38. for (int i = 0; i < roles.Length; ++i)
  39. {
  40. m_roles[i] = roles[i];
  41. }
  42. }
  43. else
  44. {
  45. m_roles = null;
  46. }
  47. }
  48. public virtual IIdentity Identity => m_identity;
  49. public virtual bool IsInRole(string role)
  50. {
  51. if (role == null || m_roles == null)
  52. return false;
  53. for (int i = 0; i < m_roles.Length; ++i)
  54. {
  55. if (m_roles[i] != null && string.Compare(m_roles[i], role, StringComparison.OrdinalIgnoreCase) == 0)
  56. return true;
  57. }
  58. return false;
  59. }
  60. }
  61. }