HttpListenerContext.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. using System.Net;
  3. using System.Security.Principal;
  4. using SocketHttpListener.Net.WebSockets;
  5. using System.Threading.Tasks;
  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
  17. {
  18. get
  19. {
  20. return _response;
  21. }
  22. }
  23. public Task<HttpListenerWebSocketContext> AcceptWebSocketAsync(string subProtocol)
  24. {
  25. return AcceptWebSocketAsync(subProtocol, HttpWebSocket.DefaultReceiveBufferSize, WebSocket.DefaultKeepAliveInterval);
  26. }
  27. public Task<HttpListenerWebSocketContext> AcceptWebSocketAsync(string subProtocol, TimeSpan keepAliveInterval)
  28. {
  29. return AcceptWebSocketAsync(subProtocol, HttpWebSocket.DefaultReceiveBufferSize, keepAliveInterval);
  30. }
  31. }
  32. public class GenericPrincipal : IPrincipal
  33. {
  34. private IIdentity m_identity;
  35. private string[] m_roles;
  36. public GenericPrincipal(IIdentity identity, string[] roles)
  37. {
  38. if (identity == null)
  39. throw new ArgumentNullException("identity");
  40. m_identity = identity;
  41. if (roles != null)
  42. {
  43. m_roles = new string[roles.Length];
  44. for (int i = 0; i < roles.Length; ++i)
  45. {
  46. m_roles[i] = roles[i];
  47. }
  48. }
  49. else
  50. {
  51. m_roles = null;
  52. }
  53. }
  54. public virtual IIdentity Identity
  55. {
  56. get
  57. {
  58. return m_identity;
  59. }
  60. }
  61. public virtual bool IsInRole(string role)
  62. {
  63. if (role == null || m_roles == null)
  64. return false;
  65. for (int i = 0; i < m_roles.Length; ++i)
  66. {
  67. if (m_roles[i] != null && String.Compare(m_roles[i], role, StringComparison.OrdinalIgnoreCase) == 0)
  68. return true;
  69. }
  70. return false;
  71. }
  72. }
  73. }