AuthorizationContext.cs 10 KB

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