AuthorizationContext.cs 11 KB

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