AuthorizationContext.cs 9.9 KB

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