2
0

AuthorizationContext.cs 10 KB

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