AuthorizationContext.cs 8.0 KB

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