AuthService.cs 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. using MediaBrowser.Controller.Entities;
  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. public AuthService(IUserManager userManager, ISessionManager sessionManager, IAuthorizationContext authorizationContext)
  16. {
  17. AuthorizationContext = authorizationContext;
  18. SessionManager = sessionManager;
  19. UserManager = userManager;
  20. }
  21. public IUserManager UserManager { get; private set; }
  22. public ISessionManager SessionManager { get; private set; }
  23. public IAuthorizationContext AuthorizationContext { get; private set; }
  24. /// <summary>
  25. /// Restrict authentication to a specific <see cref="IAuthProvider"/>.
  26. /// For example, if this attribute should only permit access
  27. /// if the user is authenticated with <see cref="BasicAuthProvider"/>,
  28. /// you should set this property to <see cref="BasicAuthProvider.Name"/>.
  29. /// </summary>
  30. public string Provider { get; set; }
  31. /// <summary>
  32. /// Redirect the client to a specific URL if authentication failed.
  33. /// If this property is null, simply `401 Unauthorized` is returned.
  34. /// </summary>
  35. public string HtmlRedirect { get; set; }
  36. public void Authenticate(IRequest req, IResponse res, object requestDto)
  37. {
  38. if (HostContext.HasValidAuthSecret(req))
  39. return;
  40. ExecuteBasic(req, res, requestDto); //first check if session is authenticated
  41. if (res.IsClosed) return; //AuthenticateAttribute already closed the request (ie auth failed)
  42. ValidateUser(req);
  43. }
  44. private void ValidateUser(IRequest req)
  45. {
  46. //This code is executed before the service
  47. var auth = AuthorizationContext.GetAuthorizationInfo(req);
  48. if (string.IsNullOrWhiteSpace(auth.Token))
  49. {
  50. // Legacy
  51. // TODO: Deprecate this in Oct 2014
  52. User user = null;
  53. if (!string.IsNullOrWhiteSpace(auth.UserId))
  54. {
  55. var userId = auth.UserId;
  56. user = UserManager.GetUserById(new Guid(userId));
  57. }
  58. if (user == null || user.Configuration.IsDisabled)
  59. {
  60. throw new UnauthorizedAccessException("Unauthorized access.");
  61. }
  62. }
  63. else
  64. {
  65. SessionManager.ValidateSecurityToken(auth.Token);
  66. }
  67. }
  68. private void ExecuteBasic(IRequest req, IResponse res, object requestDto)
  69. {
  70. if (AuthenticateService.AuthProviders == null)
  71. throw new InvalidOperationException(
  72. "The AuthService must be initialized by calling AuthService.Init to use an authenticate attribute");
  73. var matchingOAuthConfigs = AuthenticateService.AuthProviders.Where(x =>
  74. this.Provider.IsNullOrEmpty()
  75. || x.Provider == this.Provider).ToList();
  76. if (matchingOAuthConfigs.Count == 0)
  77. {
  78. res.WriteError(req, requestDto, "No OAuth Configs found matching {0} provider"
  79. .Fmt(this.Provider ?? "any"));
  80. res.EndRequest();
  81. }
  82. matchingOAuthConfigs.OfType<IAuthWithRequest>()
  83. .Each(x => x.PreAuthenticate(req, res));
  84. var session = req.GetSession();
  85. if (session == null || !matchingOAuthConfigs.Any(x => session.IsAuthorized(x.Provider)))
  86. {
  87. if (this.DoHtmlRedirectIfConfigured(req, res, true)) return;
  88. AuthProvider.HandleFailedAuth(matchingOAuthConfigs[0], session, req, res);
  89. }
  90. }
  91. private void LogRequest()
  92. {
  93. }
  94. protected bool DoHtmlRedirectIfConfigured(IRequest req, IResponse res, bool includeRedirectParam = false)
  95. {
  96. var htmlRedirect = this.HtmlRedirect ?? AuthenticateService.HtmlRedirect;
  97. if (htmlRedirect != null && req.ResponseContentType.MatchesContentType(MimeTypes.Html))
  98. {
  99. DoHtmlRedirect(htmlRedirect, req, res, includeRedirectParam);
  100. return true;
  101. }
  102. return false;
  103. }
  104. public static void DoHtmlRedirect(string redirectUrl, IRequest req, IResponse res, bool includeRedirectParam)
  105. {
  106. var url = req.ResolveAbsoluteUrl(redirectUrl);
  107. if (includeRedirectParam)
  108. {
  109. var absoluteRequestPath = req.ResolveAbsoluteUrl("~" + req.PathInfo + ToQueryString(req.QueryString));
  110. url = url.AddQueryParam(HostContext.ResolveLocalizedString(LocalizedStrings.Redirect), absoluteRequestPath);
  111. }
  112. res.RedirectToUrl(url);
  113. }
  114. private static string ToQueryString(INameValueCollection queryStringCollection)
  115. {
  116. return ToQueryString((NameValueCollection)queryStringCollection.Original);
  117. }
  118. private static string ToQueryString(NameValueCollection queryStringCollection)
  119. {
  120. if (queryStringCollection == null || queryStringCollection.Count == 0)
  121. return String.Empty;
  122. return "?" + queryStringCollection.ToFormUrlEncoded();
  123. }
  124. }
  125. }