AuthorizationContext.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Threading.Tasks;
  7. using MediaBrowser.Common.Extensions;
  8. using MediaBrowser.Controller.Library;
  9. using MediaBrowser.Controller.Net;
  10. using Microsoft.AspNetCore.Http;
  11. using Microsoft.Net.Http.Headers;
  12. namespace Jellyfin.Server.Implementations.Security
  13. {
  14. public class AuthorizationContext : IAuthorizationContext
  15. {
  16. private readonly JellyfinDbProvider _jellyfinDbProvider;
  17. private readonly IUserManager _userManager;
  18. public AuthorizationContext(JellyfinDbProvider jellyfinDb, IUserManager userManager)
  19. {
  20. _jellyfinDbProvider = jellyfinDb;
  21. _userManager = userManager;
  22. }
  23. public Task<AuthorizationInfo> GetAuthorizationInfo(HttpContext requestContext)
  24. {
  25. if (requestContext.Request.HttpContext.Items.TryGetValue("AuthorizationInfo", out var cached) && cached != null)
  26. {
  27. return Task.FromResult((AuthorizationInfo)cached);
  28. }
  29. return GetAuthorization(requestContext);
  30. }
  31. public async Task<AuthorizationInfo> GetAuthorizationInfo(HttpRequest requestContext)
  32. {
  33. var auth = GetAuthorizationDictionary(requestContext);
  34. var authInfo = await GetAuthorizationInfoFromDictionary(auth, requestContext.Headers, requestContext.Query).ConfigureAwait(false);
  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 async Task<AuthorizationInfo> GetAuthorization(HttpContext httpReq)
  43. {
  44. var auth = GetAuthorizationDictionary(httpReq);
  45. var authInfo = await GetAuthorizationInfoFromDictionary(auth, httpReq.Request.Headers, httpReq.Request.Query).ConfigureAwait(false);
  46. httpReq.Request.HttpContext.Items["AuthorizationInfo"] = authInfo;
  47. return authInfo;
  48. }
  49. private async Task<AuthorizationInfo> GetAuthorizationInfoFromDictionary(
  50. IReadOnlyDictionary<string, string>? auth,
  51. IHeaderDictionary headers,
  52. IQueryCollection queryString)
  53. {
  54. string? deviceId = null;
  55. string? deviceName = null;
  56. string? client = null;
  57. string? version = null;
  58. string? token = null;
  59. if (auth != null)
  60. {
  61. auth.TryGetValue("DeviceId", out deviceId);
  62. auth.TryGetValue("Device", out deviceName);
  63. auth.TryGetValue("Client", out client);
  64. auth.TryGetValue("Version", out version);
  65. auth.TryGetValue("Token", out token);
  66. }
  67. #pragma warning disable CA1508
  68. // headers can return StringValues.Empty
  69. if (string.IsNullOrEmpty(token))
  70. {
  71. token = headers["X-Emby-Token"];
  72. }
  73. if (string.IsNullOrEmpty(token))
  74. {
  75. token = headers["X-MediaBrowser-Token"];
  76. }
  77. if (string.IsNullOrEmpty(token))
  78. {
  79. token = queryString["ApiKey"];
  80. }
  81. // TODO deprecate this query parameter.
  82. if (string.IsNullOrEmpty(token))
  83. {
  84. token = queryString["api_key"];
  85. }
  86. var authInfo = new AuthorizationInfo
  87. {
  88. Client = client,
  89. Device = deviceName,
  90. DeviceId = deviceId,
  91. Version = version,
  92. Token = token,
  93. IsAuthenticated = false,
  94. HasToken = false
  95. };
  96. if (string.IsNullOrWhiteSpace(token))
  97. {
  98. // Request doesn't contain a token.
  99. return authInfo;
  100. }
  101. #pragma warning restore CA1508
  102. authInfo.HasToken = true;
  103. await using var jellyfinDb = _jellyfinDbProvider.CreateContext();
  104. var device = await jellyfinDb.Devices.FirstOrDefaultAsync(d => d.AccessToken == token).ConfigureAwait(false);
  105. if (device != null)
  106. {
  107. authInfo.IsAuthenticated = true;
  108. }
  109. if (device != null)
  110. {
  111. var updateToken = false;
  112. // TODO: Remove these checks for IsNullOrWhiteSpace
  113. if (string.IsNullOrWhiteSpace(authInfo.Client))
  114. {
  115. authInfo.Client = device.AppName;
  116. }
  117. if (string.IsNullOrWhiteSpace(authInfo.DeviceId))
  118. {
  119. authInfo.DeviceId = device.DeviceId;
  120. }
  121. // Temporary. TODO - allow clients to specify that the token has been shared with a casting device
  122. var allowTokenInfoUpdate = !authInfo.Client.Contains("chromecast", StringComparison.OrdinalIgnoreCase);
  123. if (string.IsNullOrWhiteSpace(authInfo.Device))
  124. {
  125. authInfo.Device = device.DeviceName;
  126. }
  127. else if (!string.Equals(authInfo.Device, device.DeviceName, StringComparison.OrdinalIgnoreCase))
  128. {
  129. if (allowTokenInfoUpdate)
  130. {
  131. updateToken = true;
  132. device.DeviceName = authInfo.Device;
  133. }
  134. }
  135. if (string.IsNullOrWhiteSpace(authInfo.Version))
  136. {
  137. authInfo.Version = device.AppVersion;
  138. }
  139. else if (!string.Equals(authInfo.Version, device.AppVersion, StringComparison.OrdinalIgnoreCase))
  140. {
  141. if (allowTokenInfoUpdate)
  142. {
  143. updateToken = true;
  144. device.AppVersion = authInfo.Version;
  145. }
  146. }
  147. if ((DateTime.UtcNow - device.DateLastActivity).TotalMinutes > 3)
  148. {
  149. device.DateLastActivity = DateTime.UtcNow;
  150. updateToken = true;
  151. }
  152. if (!device.UserId.Equals(Guid.Empty))
  153. {
  154. authInfo.User = _userManager.GetUserById(device.UserId);
  155. authInfo.IsApiKey = false;
  156. }
  157. else
  158. {
  159. authInfo.IsApiKey = true;
  160. }
  161. if (updateToken)
  162. {
  163. jellyfinDb.Devices.Update(device);
  164. await jellyfinDb.SaveChangesAsync().ConfigureAwait(false);
  165. }
  166. }
  167. return authInfo;
  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 static 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 auth.Count > 0 ? GetAuthorization(auth[0]) : null;
  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 static 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 auth.Count > 0 ? GetAuthorization(auth[0]) : null;
  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 static Dictionary<string, string>? GetAuthorization(ReadOnlySpan<char> authorizationHeader)
  203. {
  204. var firstSpace = authorizationHeader.IndexOf(' ');
  205. // There should be at least two parts
  206. if (firstSpace == -1)
  207. {
  208. return null;
  209. }
  210. var name = authorizationHeader[..firstSpace];
  211. if (!name.Equals("MediaBrowser", StringComparison.OrdinalIgnoreCase)
  212. && !name.Equals("Emby", StringComparison.OrdinalIgnoreCase))
  213. {
  214. return null;
  215. }
  216. authorizationHeader = authorizationHeader[(firstSpace + 1)..];
  217. var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  218. foreach (var item in authorizationHeader.Split(','))
  219. {
  220. var trimmedItem = item.Trim();
  221. var firstEqualsSign = trimmedItem.IndexOf('=');
  222. if (firstEqualsSign > 0)
  223. {
  224. var key = trimmedItem[..firstEqualsSign].ToString();
  225. var value = NormalizeValue(trimmedItem[(firstEqualsSign + 1)..].Trim('"').ToString());
  226. result[key] = 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. }