AuthorizationContext.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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="httpContext">The HTTP context.</param>
  46. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  47. private async Task<AuthorizationInfo> GetAuthorization(HttpContext httpContext)
  48. {
  49. var authInfo = await GetAuthorizationInfo(httpContext.Request).ConfigureAwait(false);
  50. httpContext.Request.HttpContext.Items["AuthorizationInfo"] = authInfo;
  51. return authInfo;
  52. }
  53. private async Task<AuthorizationInfo> GetAuthorizationInfoFromDictionary(
  54. Dictionary<string, string>? auth,
  55. IHeaderDictionary headers,
  56. IQueryCollection queryString)
  57. {
  58. string? deviceId = null;
  59. string? deviceName = null;
  60. string? client = null;
  61. string? version = null;
  62. string? token = null;
  63. if (auth is not null)
  64. {
  65. auth.TryGetValue("DeviceId", out deviceId);
  66. auth.TryGetValue("Device", out deviceName);
  67. auth.TryGetValue("Client", out client);
  68. auth.TryGetValue("Version", out version);
  69. auth.TryGetValue("Token", out token);
  70. }
  71. if (string.IsNullOrEmpty(token))
  72. {
  73. token = headers["X-Emby-Token"];
  74. }
  75. if (string.IsNullOrEmpty(token))
  76. {
  77. token = headers["X-MediaBrowser-Token"];
  78. }
  79. if (string.IsNullOrEmpty(token))
  80. {
  81. token = queryString["ApiKey"];
  82. }
  83. // TODO deprecate this query parameter.
  84. if (string.IsNullOrEmpty(token))
  85. {
  86. token = queryString["api_key"];
  87. }
  88. var authInfo = new AuthorizationInfo
  89. {
  90. Client = client,
  91. Device = deviceName,
  92. DeviceId = deviceId,
  93. Version = version,
  94. Token = token,
  95. IsAuthenticated = false,
  96. HasToken = false
  97. };
  98. if (string.IsNullOrWhiteSpace(token))
  99. {
  100. // Request doesn't contain a token.
  101. return authInfo;
  102. }
  103. authInfo.HasToken = true;
  104. var dbContext = await _jellyfinDbProvider.CreateDbContextAsync().ConfigureAwait(false);
  105. await using (dbContext.ConfigureAwait(false))
  106. {
  107. var device = await dbContext.Devices.FirstOrDefaultAsync(d => d.AccessToken == token).ConfigureAwait(false);
  108. if (device is not null)
  109. {
  110. authInfo.IsAuthenticated = true;
  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. authInfo.User = _userManager.GetUserById(device.UserId);
  153. if (updateToken)
  154. {
  155. dbContext.Devices.Update(device);
  156. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  157. }
  158. }
  159. else
  160. {
  161. var key = await dbContext.ApiKeys.FirstOrDefaultAsync(apiKey => apiKey.AccessToken == token).ConfigureAwait(false);
  162. if (key is not null)
  163. {
  164. authInfo.IsAuthenticated = true;
  165. authInfo.Client = key.Name;
  166. authInfo.Token = key.AccessToken;
  167. if (string.IsNullOrWhiteSpace(authInfo.DeviceId))
  168. {
  169. authInfo.DeviceId = _serverApplicationHost.SystemId;
  170. }
  171. if (string.IsNullOrWhiteSpace(authInfo.Device))
  172. {
  173. authInfo.Device = _serverApplicationHost.Name;
  174. }
  175. if (string.IsNullOrWhiteSpace(authInfo.Version))
  176. {
  177. authInfo.Version = _serverApplicationHost.ApplicationVersionString;
  178. }
  179. authInfo.IsApiKey = true;
  180. }
  181. }
  182. return authInfo;
  183. }
  184. }
  185. /// <summary>
  186. /// Gets the auth.
  187. /// </summary>
  188. /// <param name="httpReq">The HTTP request.</param>
  189. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  190. private static Dictionary<string, string>? GetAuthorizationDictionary(HttpRequest httpReq)
  191. {
  192. var auth = httpReq.Headers["X-Emby-Authorization"];
  193. if (string.IsNullOrEmpty(auth))
  194. {
  195. auth = httpReq.Headers[HeaderNames.Authorization];
  196. }
  197. return auth.Count > 0 ? GetAuthorization(auth[0]) : null;
  198. }
  199. /// <summary>
  200. /// Gets the authorization.
  201. /// </summary>
  202. /// <param name="authorizationHeader">The authorization header.</param>
  203. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  204. private static Dictionary<string, string>? GetAuthorization(ReadOnlySpan<char> authorizationHeader)
  205. {
  206. var firstSpace = authorizationHeader.IndexOf(' ');
  207. // There should be at least two parts
  208. if (firstSpace == -1)
  209. {
  210. return null;
  211. }
  212. var name = authorizationHeader[..firstSpace];
  213. if (!name.Equals("MediaBrowser", StringComparison.OrdinalIgnoreCase)
  214. && !name.Equals("Emby", StringComparison.OrdinalIgnoreCase))
  215. {
  216. return null;
  217. }
  218. // Remove up until the first space
  219. authorizationHeader = authorizationHeader[(firstSpace + 1)..];
  220. return GetParts(authorizationHeader);
  221. }
  222. /// <summary>
  223. /// Get the authorization header components.
  224. /// </summary>
  225. /// <param name="authorizationHeader">The authorization header.</param>
  226. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  227. public static Dictionary<string, string> GetParts(ReadOnlySpan<char> authorizationHeader)
  228. {
  229. var result = new Dictionary<string, string>();
  230. var escaped = false;
  231. int start = 0;
  232. string key = string.Empty;
  233. int i;
  234. for (i = 0; i < authorizationHeader.Length; i++)
  235. {
  236. var token = authorizationHeader[i];
  237. if (token == '"' || token == ',')
  238. {
  239. // Applying a XOR logic to evaluate whether it is opening or closing a value
  240. escaped = (!escaped) == (token == '"');
  241. if (token == ',' && !escaped)
  242. {
  243. // Meeting a comma after a closing escape char means the value is complete
  244. if (start < i)
  245. {
  246. result[key] = WebUtility.UrlDecode(authorizationHeader[start..i].Trim('"').ToString());
  247. key = string.Empty;
  248. }
  249. start = i + 1;
  250. }
  251. }
  252. else if (!escaped && token == '=')
  253. {
  254. key = authorizationHeader[start.. i].Trim().ToString();
  255. start = i + 1;
  256. }
  257. }
  258. // Add last value
  259. if (start < i)
  260. {
  261. result[key] = WebUtility.UrlDecode(authorizationHeader[start..i].Trim('"').ToString());
  262. }
  263. return result;
  264. }
  265. }
  266. }