AuthorizationContext.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using MediaBrowser.Controller.Library;
  5. using MediaBrowser.Controller.Net;
  6. using MediaBrowser.Controller.Security;
  7. using MediaBrowser.Model.Services;
  8. using Microsoft.Net.Http.Headers;
  9. namespace Emby.Server.Implementations.HttpServer.Security
  10. {
  11. public class AuthorizationContext : IAuthorizationContext
  12. {
  13. private readonly IAuthenticationRepository _authRepo;
  14. private readonly IUserManager _userManager;
  15. public AuthorizationContext(IAuthenticationRepository authRepo, IUserManager userManager)
  16. {
  17. _authRepo = authRepo;
  18. _userManager = userManager;
  19. }
  20. public AuthorizationInfo GetAuthorizationInfo(object requestContext)
  21. {
  22. return GetAuthorizationInfo((IRequest)requestContext);
  23. }
  24. public AuthorizationInfo GetAuthorizationInfo(IRequest requestContext)
  25. {
  26. if (requestContext.Items.TryGetValue("AuthorizationInfo", out var cached))
  27. {
  28. return (AuthorizationInfo)cached;
  29. }
  30. return GetAuthorization(requestContext);
  31. }
  32. /// <summary>
  33. /// Gets the authorization.
  34. /// </summary>
  35. /// <param name="httpReq">The HTTP req.</param>
  36. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  37. private AuthorizationInfo GetAuthorization(IRequest httpReq)
  38. {
  39. var auth = GetAuthorizationDictionary(httpReq);
  40. string deviceId = null;
  41. string device = null;
  42. string client = null;
  43. string version = null;
  44. string token = null;
  45. if (auth != null)
  46. {
  47. auth.TryGetValue("DeviceId", out deviceId);
  48. auth.TryGetValue("Device", out device);
  49. auth.TryGetValue("Client", out client);
  50. auth.TryGetValue("Version", out version);
  51. auth.TryGetValue("Token", out token);
  52. }
  53. if (string.IsNullOrEmpty(token))
  54. {
  55. token = httpReq.Headers["X-Emby-Token"];
  56. }
  57. if (string.IsNullOrEmpty(token))
  58. {
  59. token = httpReq.Headers["X-MediaBrowser-Token"];
  60. }
  61. if (string.IsNullOrEmpty(token))
  62. {
  63. token = httpReq.QueryString["api_key"];
  64. }
  65. var info = new AuthorizationInfo
  66. {
  67. Client = client,
  68. Device = device,
  69. DeviceId = deviceId,
  70. Version = version,
  71. Token = token
  72. };
  73. if (!string.IsNullOrWhiteSpace(token))
  74. {
  75. var result = _authRepo.Get(new AuthenticationInfoQuery
  76. {
  77. AccessToken = token
  78. });
  79. var tokenInfo = result.Items.Length > 0 ? result.Items[0] : null;
  80. if (tokenInfo != null)
  81. {
  82. var updateToken = false;
  83. // TODO: Remove these checks for IsNullOrWhiteSpace
  84. if (string.IsNullOrWhiteSpace(info.Client))
  85. {
  86. info.Client = tokenInfo.AppName;
  87. }
  88. if (string.IsNullOrWhiteSpace(info.DeviceId))
  89. {
  90. info.DeviceId = tokenInfo.DeviceId;
  91. }
  92. // Temporary. TODO - allow clients to specify that the token has been shared with a casting device
  93. var allowTokenInfoUpdate = info.Client == null || info.Client.IndexOf("chromecast", StringComparison.OrdinalIgnoreCase) == -1;
  94. if (string.IsNullOrWhiteSpace(info.Device))
  95. {
  96. info.Device = tokenInfo.DeviceName;
  97. }
  98. else if (!string.Equals(info.Device, tokenInfo.DeviceName, StringComparison.OrdinalIgnoreCase))
  99. {
  100. if (allowTokenInfoUpdate)
  101. {
  102. updateToken = true;
  103. tokenInfo.DeviceName = info.Device;
  104. }
  105. }
  106. if (string.IsNullOrWhiteSpace(info.Version))
  107. {
  108. info.Version = tokenInfo.AppVersion;
  109. }
  110. else if (!string.Equals(info.Version, tokenInfo.AppVersion, StringComparison.OrdinalIgnoreCase))
  111. {
  112. if (allowTokenInfoUpdate)
  113. {
  114. updateToken = true;
  115. tokenInfo.AppVersion = info.Version;
  116. }
  117. }
  118. if ((DateTime.UtcNow - tokenInfo.DateLastActivity).TotalMinutes > 3)
  119. {
  120. tokenInfo.DateLastActivity = DateTime.UtcNow;
  121. updateToken = true;
  122. }
  123. if (!tokenInfo.UserId.Equals(Guid.Empty))
  124. {
  125. info.User = _userManager.GetUserById(tokenInfo.UserId);
  126. if (info.User != null && !string.Equals(info.User.Name, tokenInfo.UserName, StringComparison.OrdinalIgnoreCase))
  127. {
  128. tokenInfo.UserName = info.User.Name;
  129. updateToken = true;
  130. }
  131. }
  132. if (updateToken)
  133. {
  134. _authRepo.Update(tokenInfo);
  135. }
  136. }
  137. httpReq.Items["OriginalAuthenticationInfo"] = tokenInfo;
  138. }
  139. httpReq.Items["AuthorizationInfo"] = info;
  140. return info;
  141. }
  142. /// <summary>
  143. /// Gets the auth.
  144. /// </summary>
  145. /// <param name="httpReq">The HTTP req.</param>
  146. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  147. private Dictionary<string, string> GetAuthorizationDictionary(IRequest httpReq)
  148. {
  149. var auth = httpReq.Headers["X-Emby-Authorization"];
  150. if (string.IsNullOrEmpty(auth))
  151. {
  152. auth = httpReq.Headers[HeaderNames.Authorization];
  153. }
  154. return GetAuthorization(auth);
  155. }
  156. /// <summary>
  157. /// Gets the authorization.
  158. /// </summary>
  159. /// <param name="authorizationHeader">The authorization header.</param>
  160. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  161. private Dictionary<string, string> GetAuthorization(string authorizationHeader)
  162. {
  163. if (authorizationHeader == null) return null;
  164. var parts = authorizationHeader.Split(new[] { ' ' }, 2);
  165. // There should be at least to parts
  166. if (parts.Length != 2) return null;
  167. var acceptedNames = new[] { "MediaBrowser", "Emby" };
  168. // It has to be a digest request
  169. if (!acceptedNames.Contains(parts[0] ?? string.Empty, StringComparer.OrdinalIgnoreCase))
  170. {
  171. return null;
  172. }
  173. // Remove uptil the first space
  174. authorizationHeader = parts[1];
  175. parts = authorizationHeader.Split(',');
  176. var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  177. foreach (var item in parts)
  178. {
  179. var param = item.Trim().Split(new[] { '=' }, 2);
  180. if (param.Length == 2)
  181. {
  182. var value = NormalizeValue(param[1].Trim(new[] { '"' }));
  183. result.Add(param[0], value);
  184. }
  185. }
  186. return result;
  187. }
  188. private static string NormalizeValue(string value)
  189. {
  190. if (string.IsNullOrEmpty(value))
  191. {
  192. return value;
  193. }
  194. return System.Net.WebUtility.HtmlEncode(value);
  195. }
  196. }
  197. }