AuthorizationContext.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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. HasToken = false
  106. };
  107. if (string.IsNullOrWhiteSpace(token))
  108. {
  109. // Request doesn't contain a token.
  110. return authInfo;
  111. }
  112. authInfo.HasToken = true;
  113. var dbContext = await _jellyfinDbProvider.CreateDbContextAsync().ConfigureAwait(false);
  114. await using (dbContext.ConfigureAwait(false))
  115. {
  116. var device = _deviceManager.GetDevices(
  117. new DeviceQuery { AccessToken = token }).Items.FirstOrDefault();
  118. if (device is not null)
  119. {
  120. authInfo.IsAuthenticated = true;
  121. var updateToken = false;
  122. // TODO: Remove these checks for IsNullOrWhiteSpace
  123. if (string.IsNullOrWhiteSpace(authInfo.Client))
  124. {
  125. authInfo.Client = device.AppName;
  126. }
  127. if (string.IsNullOrWhiteSpace(authInfo.DeviceId))
  128. {
  129. authInfo.DeviceId = device.DeviceId;
  130. }
  131. // Temporary. TODO - allow clients to specify that the token has been shared with a casting device
  132. var allowTokenInfoUpdate = !authInfo.Client.Contains("chromecast", StringComparison.OrdinalIgnoreCase);
  133. if (string.IsNullOrWhiteSpace(authInfo.Device))
  134. {
  135. authInfo.Device = device.DeviceName;
  136. }
  137. else if (!string.Equals(authInfo.Device, device.DeviceName, StringComparison.OrdinalIgnoreCase))
  138. {
  139. if (allowTokenInfoUpdate)
  140. {
  141. updateToken = true;
  142. device.DeviceName = authInfo.Device;
  143. }
  144. }
  145. if (string.IsNullOrWhiteSpace(authInfo.Version))
  146. {
  147. authInfo.Version = device.AppVersion;
  148. }
  149. else if (!string.Equals(authInfo.Version, device.AppVersion, StringComparison.OrdinalIgnoreCase))
  150. {
  151. if (allowTokenInfoUpdate)
  152. {
  153. updateToken = true;
  154. device.AppVersion = authInfo.Version;
  155. }
  156. }
  157. if ((DateTime.UtcNow - device.DateLastActivity).TotalMinutes > 3)
  158. {
  159. device.DateLastActivity = DateTime.UtcNow;
  160. updateToken = true;
  161. }
  162. authInfo.User = _userManager.GetUserById(device.UserId);
  163. if (updateToken)
  164. {
  165. await _deviceManager.UpdateDevice(device).ConfigureAwait(false);
  166. }
  167. }
  168. else
  169. {
  170. var key = await dbContext.ApiKeys.FirstOrDefaultAsync(apiKey => apiKey.AccessToken == token).ConfigureAwait(false);
  171. if (key is not null)
  172. {
  173. authInfo.IsAuthenticated = true;
  174. authInfo.Client = key.Name;
  175. authInfo.Token = key.AccessToken;
  176. if (string.IsNullOrWhiteSpace(authInfo.DeviceId))
  177. {
  178. authInfo.DeviceId = _serverApplicationHost.SystemId;
  179. }
  180. if (string.IsNullOrWhiteSpace(authInfo.Device))
  181. {
  182. authInfo.Device = _serverApplicationHost.Name;
  183. }
  184. if (string.IsNullOrWhiteSpace(authInfo.Version))
  185. {
  186. authInfo.Version = _serverApplicationHost.ApplicationVersionString;
  187. }
  188. authInfo.IsApiKey = true;
  189. }
  190. }
  191. return authInfo;
  192. }
  193. }
  194. /// <summary>
  195. /// Gets the auth.
  196. /// </summary>
  197. /// <param name="httpReq">The HTTP request.</param>
  198. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  199. private Dictionary<string, string>? GetAuthorizationDictionary(HttpRequest httpReq)
  200. {
  201. var auth = httpReq.Headers[HeaderNames.Authorization];
  202. if (_configurationManager.Configuration.EnableLegacyAuthorization && string.IsNullOrEmpty(auth))
  203. {
  204. auth = httpReq.Headers["X-Emby-Authorization"];
  205. }
  206. return auth.Count > 0 ? GetAuthorization(auth[0]) : null;
  207. }
  208. /// <summary>
  209. /// Gets the authorization.
  210. /// </summary>
  211. /// <param name="authorizationHeader">The authorization header.</param>
  212. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  213. private Dictionary<string, string>? GetAuthorization(ReadOnlySpan<char> authorizationHeader)
  214. {
  215. var firstSpace = authorizationHeader.IndexOf(' ');
  216. // There should be at least two parts
  217. if (firstSpace == -1)
  218. {
  219. return null;
  220. }
  221. var name = authorizationHeader[..firstSpace];
  222. var validName = name.Equals("MediaBrowser", StringComparison.OrdinalIgnoreCase);
  223. validName = validName || (_configurationManager.Configuration.EnableLegacyAuthorization && name.Equals("Emby", StringComparison.OrdinalIgnoreCase));
  224. if (!validName)
  225. {
  226. return null;
  227. }
  228. // Remove up until the first space
  229. authorizationHeader = authorizationHeader[(firstSpace + 1)..];
  230. return GetParts(authorizationHeader);
  231. }
  232. /// <summary>
  233. /// Get the authorization header components.
  234. /// </summary>
  235. /// <param name="authorizationHeader">The authorization header.</param>
  236. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  237. public static Dictionary<string, string> GetParts(ReadOnlySpan<char> authorizationHeader)
  238. {
  239. var result = new Dictionary<string, string>();
  240. var escaped = false;
  241. int start = 0;
  242. string key = string.Empty;
  243. int i;
  244. for (i = 0; i < authorizationHeader.Length; i++)
  245. {
  246. var token = authorizationHeader[i];
  247. if (token == '"' || token == ',')
  248. {
  249. // Applying a XOR logic to evaluate whether it is opening or closing a value
  250. escaped = (!escaped) == (token == '"');
  251. if (token == ',' && !escaped)
  252. {
  253. // Meeting a comma after a closing escape char means the value is complete
  254. if (start < i)
  255. {
  256. result[key] = WebUtility.UrlDecode(authorizationHeader[start..i].Trim('"').ToString());
  257. key = string.Empty;
  258. }
  259. start = i + 1;
  260. }
  261. }
  262. else if (!escaped && token == '=')
  263. {
  264. key = authorizationHeader[start.. i].Trim().ToString();
  265. start = i + 1;
  266. }
  267. }
  268. // Add last value
  269. if (start < i)
  270. {
  271. result[key] = WebUtility.UrlDecode(authorizationHeader[start..i].Trim('"').ToString());
  272. }
  273. return result;
  274. }
  275. }
  276. }