AuthorizationContext.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Net;
  5. using System.Threading.Tasks;
  6. using Jellyfin.Data.Queries;
  7. using Jellyfin.Extensions;
  8. using MediaBrowser.Controller;
  9. using MediaBrowser.Controller.Configuration;
  10. using MediaBrowser.Controller.Devices;
  11. using MediaBrowser.Controller.Library;
  12. using MediaBrowser.Controller.Net;
  13. using Microsoft.AspNetCore.Http;
  14. using Microsoft.EntityFrameworkCore;
  15. using Microsoft.Net.Http.Headers;
  16. namespace Jellyfin.Server.Implementations.Security
  17. {
  18. public class AuthorizationContext : IAuthorizationContext
  19. {
  20. private readonly IDbContextFactory<JellyfinDbContext> _jellyfinDbProvider;
  21. private readonly IUserManager _userManager;
  22. private readonly IDeviceManager _deviceManager;
  23. private readonly IServerApplicationHost _serverApplicationHost;
  24. private readonly IServerConfigurationManager _configurationManager;
  25. public AuthorizationContext(
  26. IDbContextFactory<JellyfinDbContext> jellyfinDb,
  27. IUserManager userManager,
  28. IDeviceManager deviceManager,
  29. IServerApplicationHost serverApplicationHost,
  30. IServerConfigurationManager configurationManager)
  31. {
  32. _jellyfinDbProvider = jellyfinDb;
  33. _userManager = userManager;
  34. _deviceManager = deviceManager;
  35. _serverApplicationHost = serverApplicationHost;
  36. _configurationManager = configurationManager;
  37. }
  38. public Task<AuthorizationInfo> GetAuthorizationInfo(HttpContext requestContext)
  39. {
  40. if (requestContext.Request.HttpContext.Items.TryGetValue("AuthorizationInfo", out var cached) && cached is not null)
  41. {
  42. return Task.FromResult((AuthorizationInfo)cached); // Cache should never contain null
  43. }
  44. return GetAuthorization(requestContext);
  45. }
  46. public async Task<AuthorizationInfo> GetAuthorizationInfo(HttpRequest requestContext)
  47. {
  48. var auth = GetAuthorizationDictionary(requestContext);
  49. var authInfo = await GetAuthorizationInfoFromDictionary(auth, requestContext.Headers, requestContext.Query).ConfigureAwait(false);
  50. return authInfo;
  51. }
  52. /// <summary>
  53. /// Gets the authorization.
  54. /// </summary>
  55. /// <param name="httpContext">The HTTP context.</param>
  56. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  57. private async Task<AuthorizationInfo> GetAuthorization(HttpContext httpContext)
  58. {
  59. var authInfo = await GetAuthorizationInfo(httpContext.Request).ConfigureAwait(false);
  60. httpContext.Request.HttpContext.Items["AuthorizationInfo"] = authInfo;
  61. return authInfo;
  62. }
  63. private async Task<AuthorizationInfo> GetAuthorizationInfoFromDictionary(
  64. Dictionary<string, string>? auth,
  65. IHeaderDictionary headers,
  66. IQueryCollection queryString)
  67. {
  68. string? deviceId = null;
  69. string? deviceName = null;
  70. string? client = null;
  71. string? version = null;
  72. string? token = null;
  73. if (auth is not null)
  74. {
  75. auth.TryGetValue("DeviceId", out deviceId);
  76. auth.TryGetValue("Device", out deviceName);
  77. auth.TryGetValue("Client", out client);
  78. auth.TryGetValue("Version", out version);
  79. auth.TryGetValue("Token", out token);
  80. }
  81. if (_configurationManager.Configuration.EnableLegacyAuthorization && string.IsNullOrEmpty(token))
  82. {
  83. token = headers["X-Emby-Token"];
  84. }
  85. if (_configurationManager.Configuration.EnableLegacyAuthorization && string.IsNullOrEmpty(token))
  86. {
  87. token = headers["X-MediaBrowser-Token"];
  88. }
  89. if (string.IsNullOrEmpty(token))
  90. {
  91. token = queryString["ApiKey"];
  92. }
  93. if (_configurationManager.Configuration.EnableLegacyAuthorization && string.IsNullOrEmpty(token))
  94. {
  95. token = queryString["api_key"];
  96. }
  97. var authInfo = new AuthorizationInfo
  98. {
  99. Client = client,
  100. Device = deviceName,
  101. DeviceId = deviceId,
  102. Version = version,
  103. Token = token,
  104. IsAuthenticated = false
  105. };
  106. if (!authInfo.HasToken)
  107. {
  108. // Request doesn't contain a token.
  109. return authInfo;
  110. }
  111. var dbContext = await _jellyfinDbProvider.CreateDbContextAsync().ConfigureAwait(false);
  112. await using (dbContext.ConfigureAwait(false))
  113. {
  114. var device = _deviceManager.GetDevices(
  115. new DeviceQuery { AccessToken = token }).Items.FirstOrDefault();
  116. if (device is not null)
  117. {
  118. authInfo.IsAuthenticated = true;
  119. var updateToken = false;
  120. // TODO: Remove these checks for IsNullOrWhiteSpace
  121. if (string.IsNullOrWhiteSpace(authInfo.Client))
  122. {
  123. authInfo.Client = device.AppName;
  124. }
  125. if (string.IsNullOrWhiteSpace(authInfo.DeviceId))
  126. {
  127. authInfo.DeviceId = device.DeviceId;
  128. }
  129. // Temporary. TODO - allow clients to specify that the token has been shared with a casting device
  130. var allowTokenInfoUpdate = !authInfo.Client.Contains("chromecast", StringComparison.OrdinalIgnoreCase);
  131. if (string.IsNullOrWhiteSpace(authInfo.Device))
  132. {
  133. authInfo.Device = device.DeviceName;
  134. }
  135. else if (!string.Equals(authInfo.Device, device.DeviceName, StringComparison.OrdinalIgnoreCase))
  136. {
  137. if (allowTokenInfoUpdate)
  138. {
  139. updateToken = true;
  140. device.DeviceName = authInfo.Device;
  141. }
  142. }
  143. if (string.IsNullOrWhiteSpace(authInfo.Version))
  144. {
  145. authInfo.Version = device.AppVersion;
  146. }
  147. else if (!string.Equals(authInfo.Version, device.AppVersion, StringComparison.OrdinalIgnoreCase))
  148. {
  149. if (allowTokenInfoUpdate)
  150. {
  151. updateToken = true;
  152. device.AppVersion = authInfo.Version;
  153. }
  154. }
  155. if ((DateTime.UtcNow - device.DateLastActivity).TotalMinutes > 3)
  156. {
  157. device.DateLastActivity = DateTime.UtcNow;
  158. updateToken = true;
  159. }
  160. authInfo.User = _userManager.GetUserById(device.UserId);
  161. if (updateToken)
  162. {
  163. await _deviceManager.UpdateDevice(device).ConfigureAwait(false);
  164. }
  165. }
  166. else
  167. {
  168. var key = await dbContext.ApiKeys.FirstOrDefaultAsync(apiKey => apiKey.AccessToken == token).ConfigureAwait(false);
  169. if (key is not null)
  170. {
  171. authInfo.IsAuthenticated = true;
  172. authInfo.Client = key.Name;
  173. authInfo.Token = key.AccessToken;
  174. if (string.IsNullOrWhiteSpace(authInfo.DeviceId))
  175. {
  176. authInfo.DeviceId = _serverApplicationHost.SystemId;
  177. }
  178. if (string.IsNullOrWhiteSpace(authInfo.Device))
  179. {
  180. authInfo.Device = _serverApplicationHost.Name;
  181. }
  182. if (string.IsNullOrWhiteSpace(authInfo.Version))
  183. {
  184. authInfo.Version = _serverApplicationHost.ApplicationVersionString;
  185. }
  186. authInfo.IsApiKey = true;
  187. }
  188. }
  189. return authInfo;
  190. }
  191. }
  192. /// <summary>
  193. /// Gets the auth.
  194. /// </summary>
  195. /// <param name="httpReq">The HTTP request.</param>
  196. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  197. private Dictionary<string, string>? GetAuthorizationDictionary(HttpRequest httpReq)
  198. {
  199. var auth = httpReq.Headers[HeaderNames.Authorization];
  200. if (_configurationManager.Configuration.EnableLegacyAuthorization && string.IsNullOrEmpty(auth))
  201. {
  202. auth = httpReq.Headers["X-Emby-Authorization"];
  203. }
  204. return auth.Count > 0 ? GetAuthorization(auth[0]) : null;
  205. }
  206. /// <summary>
  207. /// Gets the authorization.
  208. /// </summary>
  209. /// <param name="authorizationHeader">The authorization header.</param>
  210. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  211. private Dictionary<string, string>? GetAuthorization(ReadOnlySpan<char> authorizationHeader)
  212. {
  213. var firstSpace = authorizationHeader.IndexOf(' ');
  214. // There should be at least two parts
  215. if (firstSpace == -1)
  216. {
  217. return null;
  218. }
  219. var name = authorizationHeader[..firstSpace];
  220. var validName = name.Equals("MediaBrowser", StringComparison.OrdinalIgnoreCase);
  221. validName = validName || (_configurationManager.Configuration.EnableLegacyAuthorization && name.Equals("Emby", StringComparison.OrdinalIgnoreCase));
  222. if (!validName)
  223. {
  224. return null;
  225. }
  226. // Remove up until the first space
  227. authorizationHeader = authorizationHeader[(firstSpace + 1)..];
  228. return GetParts(authorizationHeader);
  229. }
  230. /// <summary>
  231. /// Get the authorization header components.
  232. /// </summary>
  233. /// <param name="authorizationHeader">The authorization header.</param>
  234. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  235. public static Dictionary<string, string> GetParts(ReadOnlySpan<char> authorizationHeader)
  236. {
  237. var result = new Dictionary<string, string>();
  238. var escaped = false;
  239. int start = 0;
  240. string key = string.Empty;
  241. int i;
  242. for (i = 0; i < authorizationHeader.Length; i++)
  243. {
  244. var token = authorizationHeader[i];
  245. if (token == '"' || token == ',')
  246. {
  247. // Applying a XOR logic to evaluate whether it is opening or closing a value
  248. escaped = (!escaped) == (token == '"');
  249. if (token == ',' && !escaped)
  250. {
  251. // Meeting a comma after a closing escape char means the value is complete
  252. if (start < i)
  253. {
  254. result[key] = WebUtility.UrlDecode(authorizationHeader[start..i].Trim('"').ToString());
  255. key = string.Empty;
  256. }
  257. start = i + 1;
  258. }
  259. }
  260. else if (!escaped && token == '=')
  261. {
  262. key = authorizationHeader[start.. i].Trim().ToString();
  263. start = i + 1;
  264. }
  265. }
  266. // Add last value
  267. if (start < i)
  268. {
  269. result[key] = WebUtility.UrlDecode(authorizationHeader[start..i].Trim('"').ToString());
  270. }
  271. return result;
  272. }
  273. }
  274. }