AuthorizationContext.cs 10 KB

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