AuthorizationContext.cs 12 KB

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