AuthService.cs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. using MediaBrowser.Controller.Configuration;
  2. using MediaBrowser.Controller.Library;
  3. using MediaBrowser.Controller.Net;
  4. using MediaBrowser.Controller.Session;
  5. using ServiceStack;
  6. using ServiceStack.Auth;
  7. using ServiceStack.Web;
  8. using System;
  9. using System.Collections.Specialized;
  10. using System.Linq;
  11. namespace MediaBrowser.Server.Implementations.HttpServer.Security
  12. {
  13. public class AuthService : IAuthService
  14. {
  15. private readonly IServerConfigurationManager _config;
  16. public AuthService(IUserManager userManager, ISessionManager sessionManager, IAuthorizationContext authorizationContext, IServerConfigurationManager config)
  17. {
  18. AuthorizationContext = authorizationContext;
  19. _config = config;
  20. SessionManager = sessionManager;
  21. UserManager = userManager;
  22. }
  23. public IUserManager UserManager { get; private set; }
  24. public ISessionManager SessionManager { get; private set; }
  25. public IAuthorizationContext AuthorizationContext { get; private set; }
  26. /// <summary>
  27. /// Restrict authentication to a specific <see cref="IAuthProvider"/>.
  28. /// For example, if this attribute should only permit access
  29. /// if the user is authenticated with <see cref="BasicAuthProvider"/>,
  30. /// you should set this property to <see cref="BasicAuthProvider.Name"/>.
  31. /// </summary>
  32. public string Provider { get; set; }
  33. /// <summary>
  34. /// Redirect the client to a specific URL if authentication failed.
  35. /// If this property is null, simply `401 Unauthorized` is returned.
  36. /// </summary>
  37. public string HtmlRedirect { get; set; }
  38. public void Authenticate(IRequest request,
  39. IResponse response,
  40. object requestDto,
  41. bool allowLocal,
  42. string[] roles)
  43. {
  44. if (HostContext.HasValidAuthSecret(request))
  45. return;
  46. //ExecuteBasic(req, res, requestDto); //first check if session is authenticated
  47. //if (res.IsClosed) return; //AuthenticateAttribute already closed the request (ie auth failed)
  48. ValidateUser(request, allowLocal, roles);
  49. }
  50. private void ValidateUser(IRequest req, bool allowLocal,
  51. string[] roles)
  52. {
  53. //This code is executed before the service
  54. var auth = AuthorizationContext.GetAuthorizationInfo(req);
  55. if (!string.IsNullOrWhiteSpace(auth.Token)
  56. || _config.Configuration.SecureApps2.Contains(auth.Client ?? string.Empty, StringComparer.OrdinalIgnoreCase))
  57. {
  58. if (!allowLocal || !req.IsLocal)
  59. {
  60. SessionManager.ValidateSecurityToken(auth.Token);
  61. }
  62. }
  63. var user = string.IsNullOrWhiteSpace(auth.UserId)
  64. ? null
  65. : UserManager.GetUserById(auth.UserId);
  66. if (user == null & !string.IsNullOrWhiteSpace(auth.UserId))
  67. {
  68. throw new ArgumentException("User with Id " + auth.UserId + " not found");
  69. }
  70. if (user != null && user.Configuration.IsDisabled)
  71. {
  72. throw new AuthenticationException("User account has been disabled.");
  73. }
  74. if (roles.Contains("admin", StringComparer.OrdinalIgnoreCase))
  75. {
  76. if (user == null || !user.Configuration.IsAdministrator)
  77. {
  78. throw new ArgumentException("Administrative access is required for this request.");
  79. }
  80. }
  81. if (!string.IsNullOrWhiteSpace(auth.DeviceId) &&
  82. !string.IsNullOrWhiteSpace(auth.Client) &&
  83. !string.IsNullOrWhiteSpace(auth.Device))
  84. {
  85. SessionManager.LogSessionActivity(auth.Client,
  86. auth.Version,
  87. auth.DeviceId,
  88. auth.Device,
  89. req.RemoteIp,
  90. user);
  91. }
  92. }
  93. protected bool DoHtmlRedirectIfConfigured(IRequest req, IResponse res, bool includeRedirectParam = false)
  94. {
  95. var htmlRedirect = this.HtmlRedirect ?? AuthenticateService.HtmlRedirect;
  96. if (htmlRedirect != null && req.ResponseContentType.MatchesContentType(MimeTypes.Html))
  97. {
  98. DoHtmlRedirect(htmlRedirect, req, res, includeRedirectParam);
  99. return true;
  100. }
  101. return false;
  102. }
  103. public static void DoHtmlRedirect(string redirectUrl, IRequest req, IResponse res, bool includeRedirectParam)
  104. {
  105. var url = req.ResolveAbsoluteUrl(redirectUrl);
  106. if (includeRedirectParam)
  107. {
  108. var absoluteRequestPath = req.ResolveAbsoluteUrl("~" + req.PathInfo + ToQueryString(req.QueryString));
  109. url = url.AddQueryParam(HostContext.ResolveLocalizedString(LocalizedStrings.Redirect), absoluteRequestPath);
  110. }
  111. res.RedirectToUrl(url);
  112. }
  113. private static string ToQueryString(INameValueCollection queryStringCollection)
  114. {
  115. return ToQueryString((NameValueCollection)queryStringCollection.Original);
  116. }
  117. private static string ToQueryString(NameValueCollection queryStringCollection)
  118. {
  119. if (queryStringCollection == null || queryStringCollection.Count == 0)
  120. return String.Empty;
  121. return "?" + queryStringCollection.ToFormUrlEncoded();
  122. }
  123. }
  124. }