AuthorizationContext.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. #pragma warning disable CS1591
  2. #pragma warning disable SA1600
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Net;
  7. using MediaBrowser.Controller.Library;
  8. using MediaBrowser.Controller.Net;
  9. using MediaBrowser.Controller.Security;
  10. using MediaBrowser.Model.Services;
  11. using Microsoft.Net.Http.Headers;
  12. namespace Emby.Server.Implementations.HttpServer.Security
  13. {
  14. public class AuthorizationContext : IAuthorizationContext
  15. {
  16. private readonly IAuthenticationRepository _authRepo;
  17. private readonly IUserManager _userManager;
  18. public AuthorizationContext(IAuthenticationRepository authRepo, IUserManager userManager)
  19. {
  20. _authRepo = authRepo;
  21. _userManager = userManager;
  22. }
  23. public AuthorizationInfo GetAuthorizationInfo(object requestContext)
  24. {
  25. return GetAuthorizationInfo((IRequest)requestContext);
  26. }
  27. public AuthorizationInfo GetAuthorizationInfo(IRequest requestContext)
  28. {
  29. if (requestContext.Items.TryGetValue("AuthorizationInfo", out var cached))
  30. {
  31. return (AuthorizationInfo)cached;
  32. }
  33. return GetAuthorization(requestContext);
  34. }
  35. /// <summary>
  36. /// Gets the authorization.
  37. /// </summary>
  38. /// <param name="httpReq">The HTTP req.</param>
  39. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  40. private AuthorizationInfo GetAuthorization(IRequest httpReq)
  41. {
  42. var auth = GetAuthorizationDictionary(httpReq);
  43. string deviceId = null;
  44. string device = null;
  45. string client = null;
  46. string version = null;
  47. string token = null;
  48. if (auth != null)
  49. {
  50. auth.TryGetValue("DeviceId", out deviceId);
  51. auth.TryGetValue("Device", out device);
  52. auth.TryGetValue("Client", out client);
  53. auth.TryGetValue("Version", out version);
  54. auth.TryGetValue("Token", out token);
  55. }
  56. if (string.IsNullOrEmpty(token))
  57. {
  58. token = httpReq.Headers["X-Emby-Token"];
  59. }
  60. if (string.IsNullOrEmpty(token))
  61. {
  62. token = httpReq.Headers["X-MediaBrowser-Token"];
  63. }
  64. if (string.IsNullOrEmpty(token))
  65. {
  66. token = httpReq.QueryString["api_key"];
  67. }
  68. var info = new AuthorizationInfo
  69. {
  70. Client = client,
  71. Device = device,
  72. DeviceId = deviceId,
  73. Version = version,
  74. Token = token
  75. };
  76. if (!string.IsNullOrWhiteSpace(token))
  77. {
  78. var result = _authRepo.Get(new AuthenticationInfoQuery
  79. {
  80. AccessToken = token
  81. });
  82. var tokenInfo = result.Items.Count > 0 ? result.Items[0] : null;
  83. if (tokenInfo != null)
  84. {
  85. var updateToken = false;
  86. // TODO: Remove these checks for IsNullOrWhiteSpace
  87. if (string.IsNullOrWhiteSpace(info.Client))
  88. {
  89. info.Client = tokenInfo.AppName;
  90. }
  91. if (string.IsNullOrWhiteSpace(info.DeviceId))
  92. {
  93. info.DeviceId = tokenInfo.DeviceId;
  94. }
  95. // Temporary. TODO - allow clients to specify that the token has been shared with a casting device
  96. var allowTokenInfoUpdate = info.Client == null || info.Client.IndexOf("chromecast", StringComparison.OrdinalIgnoreCase) == -1;
  97. if (string.IsNullOrWhiteSpace(info.Device))
  98. {
  99. info.Device = tokenInfo.DeviceName;
  100. }
  101. else if (!string.Equals(info.Device, tokenInfo.DeviceName, StringComparison.OrdinalIgnoreCase))
  102. {
  103. if (allowTokenInfoUpdate)
  104. {
  105. updateToken = true;
  106. tokenInfo.DeviceName = info.Device;
  107. }
  108. }
  109. if (string.IsNullOrWhiteSpace(info.Version))
  110. {
  111. info.Version = tokenInfo.AppVersion;
  112. }
  113. else if (!string.Equals(info.Version, tokenInfo.AppVersion, StringComparison.OrdinalIgnoreCase))
  114. {
  115. if (allowTokenInfoUpdate)
  116. {
  117. updateToken = true;
  118. tokenInfo.AppVersion = info.Version;
  119. }
  120. }
  121. if ((DateTime.UtcNow - tokenInfo.DateLastActivity).TotalMinutes > 3)
  122. {
  123. tokenInfo.DateLastActivity = DateTime.UtcNow;
  124. updateToken = true;
  125. }
  126. if (!tokenInfo.UserId.Equals(Guid.Empty))
  127. {
  128. info.User = _userManager.GetUserById(tokenInfo.UserId);
  129. if (info.User != null && !string.Equals(info.User.Name, tokenInfo.UserName, StringComparison.OrdinalIgnoreCase))
  130. {
  131. tokenInfo.UserName = info.User.Name;
  132. updateToken = true;
  133. }
  134. }
  135. if (updateToken)
  136. {
  137. _authRepo.Update(tokenInfo);
  138. }
  139. }
  140. httpReq.Items["OriginalAuthenticationInfo"] = tokenInfo;
  141. }
  142. httpReq.Items["AuthorizationInfo"] = info;
  143. return info;
  144. }
  145. /// <summary>
  146. /// Gets the auth.
  147. /// </summary>
  148. /// <param name="httpReq">The HTTP req.</param>
  149. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  150. private Dictionary<string, string> GetAuthorizationDictionary(IRequest httpReq)
  151. {
  152. var auth = httpReq.Headers["X-Emby-Authorization"];
  153. if (string.IsNullOrEmpty(auth))
  154. {
  155. auth = httpReq.Headers[HeaderNames.Authorization];
  156. }
  157. return GetAuthorization(auth);
  158. }
  159. /// <summary>
  160. /// Gets the authorization.
  161. /// </summary>
  162. /// <param name="authorizationHeader">The authorization header.</param>
  163. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  164. private Dictionary<string, string> GetAuthorization(string authorizationHeader)
  165. {
  166. if (authorizationHeader == null)
  167. {
  168. return null;
  169. }
  170. var parts = authorizationHeader.Split(new[] { ' ' }, 2);
  171. // There should be at least to parts
  172. if (parts.Length != 2)
  173. {
  174. return null;
  175. }
  176. var acceptedNames = new[] { "MediaBrowser", "Emby" };
  177. // It has to be a digest request
  178. if (!acceptedNames.Contains(parts[0], StringComparer.OrdinalIgnoreCase))
  179. {
  180. return null;
  181. }
  182. // Remove uptil the first space
  183. authorizationHeader = parts[1];
  184. parts = authorizationHeader.Split(',');
  185. var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  186. foreach (var item in parts)
  187. {
  188. var param = item.Trim().Split(new[] { '=' }, 2);
  189. if (param.Length == 2)
  190. {
  191. var value = NormalizeValue(param[1].Trim(new[] { '"' }));
  192. result.Add(param[0], value);
  193. }
  194. }
  195. return result;
  196. }
  197. private static string NormalizeValue(string value)
  198. {
  199. if (string.IsNullOrEmpty(value))
  200. {
  201. return value;
  202. }
  203. return WebUtility.HtmlEncode(value);
  204. }
  205. }
  206. }