public override object Logout(ServiceStack.ServiceInterface.IServiceBase service, Auth request) { BlackListRepository.Blacklist.Add(service.GetSessionId()); object logout = base.Logout(service, request); return logout; }
public static AuthResponse Login() { JsonServiceClient client = HTTPClientHelpers.GetClient(HTTPClientHelpers.RootUrl, HTTPClientHelpers.UserName, HTTPClientHelpers.Password); Auth request = new Auth { UserName = HTTPClientHelpers.UserName, Password = HTTPClientHelpers.Password }; AuthResponse response = client.Send<AuthResponse>(request); return response; }
public override bool IsAuthorized(IAuthSession session, IOAuthTokens tokens, Auth request = null) { if (request != null) { if (!LoginMatchesSession(session, request.UserName)) return false; } return tokens != null && !string.IsNullOrEmpty(tokens.AccessTokenSecret); }
public override bool IsAuthorized(IAuthSession session, IOAuthTokens tokens, Auth request = null) { if (BlackListRepository.Blacklist.Contains(session.Id)) return false; bool isAuthorized = base.IsAuthorized(session, tokens, request); return isAuthorized; }
public override object Logout(IServiceBase service, Auth request) { try { FederatedAuthentication.SessionAuthenticationModule.CookieHandler.Delete(); FederatedAuthentication.SessionAuthenticationModule.DeleteSessionTokenCookie(); } catch (Exception ex) { } return base.Logout(service, request); }
public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request) { var httpReq = authService.RequestContext.Get<IHttpRequest>(); var basicAuth = httpReq.GetBasicAuthUserAndPassword(); if (basicAuth == null) throw HttpError.Unauthorized("Invalid BasicAuth credentials"); var userName = basicAuth.Value.Key; var password = basicAuth.Value.Value; return Authenticate(authService, session, userName, password); }
public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request) { var tokens = Init(authService, ref session, request); var error = authService.RequestContext.Get<IHttpRequest>().QueryString["error"]; var hasError = !error.IsNullOrEmpty(); if (hasError) { Log.Error("Facebook error callback. {0}".Fmt(authService.RequestContext.Get<IHttpRequest>().QueryString)); return authService.Redirect(session.ReferrerUrl); } var code = authService.RequestContext.Get<IHttpRequest>().QueryString["code"]; var isPreAuthCallback = !code.IsNullOrEmpty(); if (!isPreAuthCallback) { var preAuthUrl = PreAuthUrl + "?client_id={0}&redirect_uri={1}&scope={2}" .Fmt(AppId, this.CallbackUrl.UrlEncode(), string.Join(",", Permissions)); authService.SaveSession(session, SessionExpiry); return authService.Redirect(preAuthUrl); } var accessTokenUrl = this.AccessTokenUrl + "?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}" .Fmt(AppId, this.CallbackUrl.UrlEncode(), AppSecret, code); try { var contents = accessTokenUrl.GetStringFromUrl(); var authInfo = HttpUtility.ParseQueryString(contents); tokens.AccessTokenSecret = authInfo["access_token"]; session.IsAuthenticated = true; authService.SaveSession(session, SessionExpiry); OnAuthenticated(authService, session, tokens, authInfo.ToDictionary()); //Haz access! return authService.Redirect(session.ReferrerUrl.AddHashParam("s", "1")); } catch (WebException we) { var statusCode = ((HttpWebResponse)we.Response).StatusCode; if (statusCode == HttpStatusCode.BadRequest) { return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "AccessTokenFailed")); } } //Shouldn't get here return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "Unknown")); }
public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request) { var tokens = Init(authService, ref session, request); //TODO: For now, later check for incoming URL to see from where it comes and decide... bool isAuthenticated = this.IsAuthorizedBySts(session, null, request); if (!isAuthenticated) { authService.SaveSession(session, SessionExpiry); return AuthenticateWithSTS(authService, session, request); } return CompleteAuthentication(authService, session, request, tokens); }
/// <summary> /// Remove the Users Session /// </summary> /// <param name="service"></param> /// <param name="request"></param> /// <returns></returns> public virtual object Logout(IServiceBase service, Auth request) { var session = service.GetSession(); var referrerUrl = (request != null ? request.Continue : null) ?? session.ReferrerUrl ?? service.RequestContext.GetHeader("Referer") ?? this.CallbackUrl; session.OnLogout(service); service.RemoveSession(); if (service.RequestContext.ResponseContentType == ContentType.Html && !String.IsNullOrEmpty(referrerUrl)) return service.Redirect(referrerUrl.AddHashParam("s", "-1")); return new AuthResponse(); }
public new object Post(ServiceStack.ServiceInterface.Auth.Auth request) { object response = null; bool authenticatedAtStart = this.GetSession().IsAuthenticated; unitOfWork.DoInTransaction(() => { response = base.Post(request); if (this.GetSession().IsAuthenticated&& !authenticatedAtStart) //User just authenticated, check if user exists { requestHandler.HandleRequest(this.GetSession()); } }); return(response); }
/// <summary> /// The entry point for all AuthProvider providers. Runs inside the AuthService so exceptions are treated normally. /// Overridable so you can provide your own Auth implementation. /// </summary> /// <param name="authService"></param> /// <param name="session"></param> /// <param name="request"></param> /// <returns></returns> public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request) { var tokens = Init(authService, ref session, request); //Default OAuth logic based on Twitter's OAuth workflow if (!tokens.RequestToken.IsNullOrEmpty() && !request.oauth_token.IsNullOrEmpty()) { OAuthUtils.RequestToken = tokens.RequestToken; OAuthUtils.RequestTokenSecret = tokens.RequestTokenSecret; OAuthUtils.AuthorizationToken = request.oauth_token; OAuthUtils.AuthorizationVerifier = request.oauth_verifier; if (OAuthUtils.AcquireAccessToken()) { tokens.AccessToken = OAuthUtils.AccessToken; tokens.AccessTokenSecret = OAuthUtils.AccessTokenSecret; session.IsAuthenticated = true; OnAuthenticated(authService, session, tokens, OAuthUtils.AuthInfo); authService.SaveSession(session, SessionExpiry); //Haz access! return authService.Redirect(session.ReferrerUrl.AddHashParam("s", "1")); } //No Joy :( tokens.RequestToken = null; tokens.RequestTokenSecret = null; authService.SaveSession(session, SessionExpiry); return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "AccessTokenFailed")); } if (OAuthUtils.AcquireRequestToken()) { tokens.RequestToken = OAuthUtils.RequestToken; tokens.RequestTokenSecret = OAuthUtils.RequestTokenSecret; authService.SaveSession(session, SessionExpiry); //Redirect to OAuth provider to approve access return authService.Redirect(this.AuthorizeUrl .AddQueryParam("oauth_token", tokens.RequestToken) .AddQueryParam("oauth_callback", session.ReferrerUrl)); } return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "RequestTokenFailed")); }
public override bool IsAuthorized(IAuthSession session, IOAuthTokens tokens, Auth request = null) { if (tokens != null && !string.IsNullOrEmpty(tokens.Email)) { var repository = new UserRepository(); var user = repository.GetByEmail(tokens.Email); if (user == null) { throw new InvalidOperationException("You are not a registered user!"); return false; } } if (request != null) { if (!LoginMatchesSession(session, request.UserName)) return false; } // For OpenId, AccessTokenSecret is null/empty, but UserId is populated w/ authenticated url from openId providers return tokens != null && !string.IsNullOrEmpty(tokens.UserId); }
public object Delete(Auth request) { if (ValidateFn != null) { var response = ValidateFn(this, HttpMethods.Delete, request); if (response != null) return response; } this.RemoveSession(); return new AuthResponse(); }
public object Post(Auth request) { AssertAuthProviders(); if (ValidateFn != null) { var validationResponse = ValidateFn(this, HttpMethods.Get, request); if (validationResponse != null) { return(validationResponse); } } if (request.RememberMe.HasValue) { var opt = request.RememberMe.GetValueOrDefault(false) ? SessionOptions.Permanent : SessionOptions.Temporary; base.RequestContext.Get <IHttpResponse>() .AddSessionOptions(base.RequestContext.Get <IHttpRequest>(), opt); } var provider = request.provider ?? AuthProviders[0].Provider; var oAuthConfig = GetAuthProvider(provider); if (oAuthConfig == null) { throw HttpError.NotFound("No configuration was added for OAuth provider '{0}'".Fmt(provider)); } if (request.provider == LogoutAction) { return(oAuthConfig.Logout(this, request)); } var session = this.GetSession(); var isHtml = base.RequestContext.ResponseContentType.MatchesContentType(ContentType.Html); try { var response = Authenticate(request, provider, session, oAuthConfig); var referrerUrl = request.Continue ?? session.ReferrerUrl ?? this.RequestContext.GetHeader("Referer") ?? oAuthConfig.CallbackUrl; var alreadyAuthenticated = response == null; response = response ?? new AuthResponse { UserName = session.UserName, SessionId = session.Id, ReferrerUrl = referrerUrl, }; if (isHtml) { if (alreadyAuthenticated) { return(this.Redirect(referrerUrl.AddHashParam("s", "0"))); } if (!(response is IHttpResult)) { return(new HttpResult(response) { Location = referrerUrl }); } } return(response); } catch (HttpError ex) { var errorReferrerUrl = this.RequestContext.GetHeader("Referer"); if (isHtml && errorReferrerUrl != null) { errorReferrerUrl = errorReferrerUrl.SetQueryParam("error", ex.Message); return(HttpResult.Redirect(errorReferrerUrl)); } throw; } }
public new object Get(ServiceStack.ServiceInterface.Auth.Auth request) { return(Post(request)); }
public override object Authenticate(IServiceBase authService, IAuthSession session, ServiceStack.ServiceInterface.Auth.Auth request) { object returnValue = null; unitOfWork.DoInTransaction( () => { returnValue = base.Authenticate(authService, session, request); }); return(returnValue); }
protected IOAuthTokens Init(IServiceBase authService, ref IAuthSession session, Auth request) { if (request != null && !LoginMatchesSession(session, request.UserName)) { //authService.RemoveSession(); //session = authService.GetSession(); } var requestUri = authService.RequestContext.AbsoluteUri; if (this.CallbackUrl.IsNullOrEmpty()) { this.CallbackUrl = requestUri; } if (session.ReferrerUrl.IsNullOrEmpty()) { session.ReferrerUrl = (request != null ? request.Continue : null) ?? authService.RequestContext.GetHeader("Referer"); } //TODO: This section needs to be changed if (session.ReferrerUrl.IsNullOrEmpty() || session.ReferrerUrl.IndexOf("/auth", StringComparison.OrdinalIgnoreCase) >= 0) { session.ReferrerUrl = this.RedirectUrl ?? ServiceStackHttpHandlerFactory.GetBaseUrl() ?? requestUri.Substring(0, requestUri.IndexOf("/", "https://".Length + 1, StringComparison.Ordinal)); } var tokens = session.ProviderOAuthAccess.FirstOrDefault(x => x.Provider == Provider); if (tokens == null) { session.ProviderOAuthAccess.Add(tokens = new OAuthTokens { Provider = Provider }); } return(tokens); }
private object AuthenticateWithSTS(IServiceBase authService, IAuthSession session, Auth request) { // First just try to redirect... string homeRealm = null;// this.Request["whr"]; string issuer; string realm; if (string.IsNullOrWhiteSpace(homeRealm)) { homeRealm = StsConfigSection.Settings.Issuer.Identifier; //"http://cloudsts.longscale.com/trust"; // AppSTSSection.Instance.Issuer.Identifier; } if (homeRealm == StsConfigSection.Settings.Issuer.Identifier) // "http://cloudsts.longscale.com/trust") { issuer = StsConfigSection.Settings.Issuer.Location; // "https://local.longscale.com/idsrv/issue/wsfed"; //AppSTSSection.Instance.Issuer.Location; realm = FederatedAuthentication.WSFederationAuthenticationModule.Realm; //"https://marketplace.longscale.com/"; } else { throw new InvalidOperationException("The home realm is not trusted for federation." + homeRealm); //throw new InvalidOperationException("The home realm is not trusted for federation." + homeRealm + "-" + AppSTSSection.Instance.Issuer.Identifier); } //var contextId = AppSTSSection.Instance.IssuerUri + "-" + Guid.NewGuid().ToString(); var contextId = StsConfigSection.Settings.IssuerUri + "-" + Guid.NewGuid().ToString(); // "http://appsts.longscale.com/trust" + "-" + Guid.NewGuid().ToString(); //this.CreateContextCookie(contextId, this.Request.Url.AbsoluteUri); var message = new SignInRequestMessage(new Uri(issuer), realm) { CurrentTime = DateTime.UtcNow.ToString("s", CultureInfo.InvariantCulture) + "Z", Reply = GetReplyUrl(), // For Azure environment... Context = contextId }; // HACK: to solve the issue with User not populated correctly with the informaiton // had to remove FedAuth cookies //FederatedAuthentication.SessionAuthenticationModule.CookieHandler.Delete(); //FederatedAuthentication.SessionAuthenticationModule.DeleteSessionTokenCookie(); return(authService.Redirect(message.RequestUrl)); // this.Response.Redirect(message.RequestUrl, false); }
public override object Logout(IServiceBase service, Auth request)
/// <summary> /// Authenticate against Yammer OAuth endpoint. /// </summary> /// <param name="authService"> /// The auth service. /// </param> /// <param name="session"> /// The session. /// </param> /// <param name="request"> /// The request. /// </param> /// <returns> /// The <see cref="object"/>. /// </returns> public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request) { var tokens = this.Init(authService, ref session, request); // Check if this is a callback from Yammer OAuth, // if not, get the code. var code = authService.RequestContext.Get <IHttpRequest>().QueryString["code"]; var isPreAuthCallback = !code.IsNullOrEmpty(); if (!isPreAuthCallback) { var preAuthUrl = string.Format( "{0}?client_id={1}&redirect_uri={2}", this.PreAuthUrl, this.ClientId, this.RedirectUrl.UrlEncode()); authService.SaveSession(session, this.SessionExpiry); return(authService.Redirect(preAuthUrl)); } // If access code exists, get access token to be able to call APIs. var accessTokenUrl = string.Format( "{0}?client_id={1}&client_secret={2}&code={3}", this.AccessTokenUrl, this.ClientId, this.ClientSecret, code); try { // Get access response object var contents = accessTokenUrl.GetStringFromUrl(); var authInfo = HttpUtility.ParseQueryString(contents); var authObj = JsonObject.Parse(contents); var accessToken = authObj.Object("access_token"); var userInfo = authObj.Object("user"); // Save info into user session tokens.AccessToken = accessToken.Get("token"); tokens.UserId = accessToken.Get("user_id"); tokens.UserName = userInfo.Get("name"); tokens.DisplayName = userInfo.Get("full_name"); tokens.FullName = userInfo.Get("full_name"); tokens.FirstName = userInfo.Get("first_name"); tokens.LastName = userInfo.Get("last_name"); var emails = userInfo.Object("contact").ArrayObjects("email_addresses").ConvertAll(x => new EmailAddresses { Type = x.Get("type"), Address = x.Get("address") }); var email = emails.FirstOrDefault(q => q.Type == "primary"); if (email != null) { tokens.Email = email.Address; } // Save session info incl. login state session.UserName = tokens.UserName; session.Email = tokens.Email; session.FirstName = tokens.FirstName; session.LastName = tokens.LastName; session.IsAuthenticated = true; authService.SaveSession(session, this.SessionExpiry); // Pass along this.OnAuthenticated(authService, session, tokens, authInfo.ToDictionary()); this.LoadUserAuthInfo((AuthUserSession)session, tokens, authInfo.ToDictionary()); // Has access! return(authService.Redirect(this.CallbackUrl.AddHashParam("s", "1"))); } catch (WebException webEx) { var statusCode = ((HttpWebResponse)webEx.Response).StatusCode; if (statusCode == HttpStatusCode.BadRequest) { return(authService.Redirect(this.CallbackUrl.AddHashParam("f", "AccessTokenFailed"))); } } // Unknown error, shouldn't get here. return(authService.Redirect(this.CallbackUrl.AddHashParam("f", "Unknown"))); }
public static AuthResponse Logout(JsonServiceClient client) { Auth request = new Auth { provider = "logout" }; return client.Send<AuthResponse>(request); }
public virtual void Options(Auth request) { }
public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request) { var tokens = Init(authService, ref session, request); var error = authService.RequestContext.Get<IHttpRequest>().QueryString["error"]; if (!string.IsNullOrEmpty(error)) { var error_description = authService.RequestContext.Get<IHttpRequest>().QueryString["error_description"]; return authService.Redirect(session.ReferrerUrl .AddHashParam("error", error) .AddHashParam("error_description", error_description)); } var code = authService.RequestContext.Get<IHttpRequest>().QueryString["code"]; var isPreAuthCallback = !string.IsNullOrWhiteSpace(code); if (!isPreAuthCallback) { var connection = authService.RequestContext.Get<IHttpRequest>().QueryString["connection"] ?? this.Connection; var preAuthUrl = this.PreAuthUrl + string.Format( "?client_id={0}&redirect_uri={1}&response_type=code&connection={2}", this.AppId, HttpUtility.UrlEncode(CallbackUrl), connection); authService.SaveSession(session, this.SessionExpiry); return authService.Redirect(preAuthUrl); } try { var entity = new StringBuilder() .Append(string.Format("client_id={0}&", this.AppId)) .Append(string.Format("client_secret={0}&", this.AppSecret)) .Append(string.Format("code={0}&", code)) .Append(string.Format("grant_type={0}&", "authorization_code")) .Append(string.Format("redirect_uri={0}&", HttpUtility.UrlEncode(CallbackUrl))) .Append(string.Format("type={0}", "web_server")) .ToString(); var tokenRequest = WebRequest.Create(this.AccessTokenUrl); tokenRequest.ContentType = "application/x-www-form-urlencoded"; tokenRequest.ContentLength = entity.Length; tokenRequest.Method = "POST"; using (Stream requestStream = tokenRequest.GetRequestStream()) { var writer = new StreamWriter(requestStream); writer.Write(entity); writer.Flush(); } var tokenResponse = (HttpWebResponse)tokenRequest.GetResponse(); if (tokenResponse.StatusCode == HttpStatusCode.OK) { using (var reader = new StreamReader(tokenResponse.GetResponseStream())) { var obj = JsonObject.Parse(reader.ReadToEnd()); if (obj != null) { tokens.AccessTokenSecret = obj.Get("access_token"); session.IsAuthenticated = true; authService.SaveSession(session, this.SessionExpiry); this.OnAuthenticated(authService, session, tokens, obj); // Haz access! return authService.Redirect(session.ReferrerUrl.AddHashParam("s", "1")); } } } } catch (WebException we) { var statusCode = ((HttpWebResponse)we.Response).StatusCode; if (statusCode == HttpStatusCode.BadRequest) { return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "AccessTokenFailed")); } } // Shouldn't get here return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "Unknown")); }
/// <summary> /// The entry point for all AuthProvider providers. Runs inside the AuthService so exceptions are treated normally. /// Overridable so you can provide your own Auth implementation. /// </summary> /// <param name="authService"></param> /// <param name="session"></param> /// <param name="request"></param> /// <returns></returns> public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request) { var tokens = Init(authService, ref session, request); //Default OAuth logic based on Twitter's OAuth workflow if (!tokens.RequestToken.IsNullOrEmpty() && !request.oauth_token.IsNullOrEmpty()) { OAuthUtils.RequestToken = tokens.RequestToken; OAuthUtils.RequestTokenSecret = tokens.RequestTokenSecret; OAuthUtils.AuthorizationToken = request.oauth_token; OAuthUtils.AuthorizationVerifier = request.oauth_verifier; if (OAuthUtils.AcquireAccessToken()) { tokens.AccessToken = OAuthUtils.AccessToken; tokens.AccessTokenSecret = OAuthUtils.AccessTokenSecret; session.IsAuthenticated = true; OnAuthenticated(authService, session, tokens, OAuthUtils.AuthInfo); authService.SaveSession(session, SessionExpiry); //Haz access! return(authService.Redirect(session.ReferrerUrl.AddHashParam("s", "1"))); } //No Joy :( tokens.RequestToken = null; tokens.RequestTokenSecret = null; authService.SaveSession(session, SessionExpiry); return(authService.Redirect(session.ReferrerUrl.AddHashParam("f", "AccessTokenFailed"))); } if (OAuthUtils.AcquireRequestToken()) { tokens.RequestToken = OAuthUtils.RequestToken; tokens.RequestTokenSecret = OAuthUtils.RequestTokenSecret; authService.SaveSession(session, SessionExpiry); //Redirect to OAuth provider to approve access return(authService.Redirect(this.AuthorizeUrl .AddQueryParam("oauth_token", tokens.RequestToken) .AddQueryParam("oauth_callback", session.ReferrerUrl))); } return(authService.Redirect(session.ReferrerUrl.AddHashParam("f", "RequestTokenFailed"))); }
public object Post(Auth request) { AssertAuthProviders(); if (ValidateFn != null) { var validationResponse = ValidateFn(this, HttpMethods.Get, request); if (validationResponse != null) return validationResponse; } if (request.RememberMe.HasValue) { var opt = request.RememberMe.GetValueOrDefault(false) ? SessionOptions.Permanent : SessionOptions.Temporary; base.RequestContext.Get<IHttpResponse>() .AddSessionOptions(base.RequestContext.Get<IHttpRequest>(), opt); } var provider = request.provider ?? AuthProviders[0].Provider; var oAuthConfig = GetAuthProvider(provider); if (oAuthConfig == null) throw HttpError.NotFound("No configuration was added for OAuth provider '{0}'".Fmt(provider)); if (request.provider == LogoutAction) return oAuthConfig.Logout(this, request); var session = this.GetSession(); var isHtml = base.RequestContext.ResponseContentType.MatchesContentType(ContentType.Html); try { var response = Authenticate(request, provider, session, oAuthConfig); var referrerUrl = request.Continue ?? session.ReferrerUrl ?? this.RequestContext.GetHeader("Referer") ?? oAuthConfig.CallbackUrl; var alreadyAuthenticated = response == null; response = response ?? new AuthResponse { UserName = session.UserName, SessionId = session.Id, ReferrerUrl = referrerUrl, }; if (isHtml) { if (alreadyAuthenticated) return this.Redirect(referrerUrl.AddHashParam("s", "0")); if (!(response is IHttpResult)) { return new HttpResult(response) { Location = referrerUrl }; } } return response; } catch (HttpError ex) { var errorReferrerUrl = this.RequestContext.GetHeader("Referer"); if (isHtml && errorReferrerUrl != null) { errorReferrerUrl = errorReferrerUrl.SetQueryParam("error", ex.Message); return HttpResult.Redirect(errorReferrerUrl); } throw; } }
/// <summary> /// Remove the Users Session /// </summary> /// <param name="service"></param> /// <param name="request"></param> /// <returns></returns> public virtual object Logout(IServiceBase service, Auth request) { var session = service.GetSession(); var referrerUrl = session.ReferrerUrl ?? service.RequestContext.GetHeader("Referer") ?? this.CallbackUrl; service.RemoveSession(); if (service.RequestContext.ResponseContentType == ContentType.Html) return service.Redirect(referrerUrl.AddHashParam("s", "-1")); return new AuthResponse(); }
public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request) { var tokens = Init(authService, ref session, request); var error = authService.RequestContext.Get <IHttpRequest>().QueryString["error"]; var hasError = !error.IsNullOrEmpty(); if (hasError) { Log.Error("Facebook error callback. {0}".Fmt(authService.RequestContext.Get <IHttpRequest>().QueryString)); return(authService.Redirect(session.ReferrerUrl)); } var code = authService.RequestContext.Get <IHttpRequest>().QueryString["code"]; var isPreAuthCallback = !code.IsNullOrEmpty(); if (!isPreAuthCallback) { var preAuthUrl = PreAuthUrl + "?client_id={0}&redirect_uri={1}&scope={2}" .Fmt(AppId, this.CallbackUrl.UrlEncode(), string.Join(",", Permissions)); authService.SaveSession(session, SessionExpiry); return(authService.Redirect(preAuthUrl)); } var accessTokenUrl = this.AccessTokenUrl + "?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}" .Fmt(AppId, this.CallbackUrl.UrlEncode(), AppSecret, code); try { var contents = accessTokenUrl.GetStringFromUrl(); var authInfo = HttpUtility.ParseQueryString(contents); tokens.AccessTokenSecret = authInfo["access_token"]; session.IsAuthenticated = true; authService.SaveSession(session, SessionExpiry); OnAuthenticated(authService, session, tokens, authInfo.ToDictionary()); //Haz access! return(authService.Redirect(session.ReferrerUrl.AddHashParam("s", "1"))); } catch (WebException we) { var statusCode = ((HttpWebResponse)we.Response).StatusCode; if (statusCode == HttpStatusCode.BadRequest) { return(authService.Redirect(session.ReferrerUrl.AddHashParam("f", "AccessTokenFailed"))); } } //Shouldn't get here return(authService.Redirect(session.ReferrerUrl.AddHashParam("f", "Unknown"))); }
public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request) { var httpReq = authService.RequestContext.Get <IHttpRequest>(); var basicAuth = httpReq.GetBasicAuthUserAndPassword(); if (basicAuth == null) { throw HttpError.Unauthorized("Invalid BasicAuth credentials"); } var userName = basicAuth.Value.Key; var password = basicAuth.Value.Value; return(Authenticate(authService, session, userName, password, request.Continue)); }
/// <summary> /// Authenticate against Yammer OAuth endpoint. /// </summary> /// <param name="authService"> /// The auth service. /// </param> /// <param name="session"> /// The session. /// </param> /// <param name="request"> /// The request. /// </param> /// <returns> /// The <see cref="object"/>. /// </returns> public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request) { var tokens = this.Init(authService, ref session, request); // Check if this is a callback from Yammer OAuth, // if not, get the code. var code = authService.RequestContext.Get<IHttpRequest>().QueryString["code"]; var isPreAuthCallback = !code.IsNullOrEmpty(); if (!isPreAuthCallback) { var preAuthUrl = string.Format( "{0}?client_id={1}&redirect_uri={2}", this.PreAuthUrl, this.ClientId, this.RedirectUrl.UrlEncode()); authService.SaveSession(session, this.SessionExpiry); return authService.Redirect(preAuthUrl); } // If access code exists, get access token to be able to call APIs. var accessTokenUrl = string.Format( "{0}?client_id={1}&client_secret={2}&code={3}", this.AccessTokenUrl, this.ClientId, this.ClientSecret, code); try { // Get access response object var contents = accessTokenUrl.GetStringFromUrl(); var authInfo = HttpUtility.ParseQueryString(contents); var authObj = JsonObject.Parse(contents); var accessToken = authObj.Object("access_token"); var userInfo = authObj.Object("user"); // Save info into user session tokens.AccessToken = accessToken.Get("token"); tokens.UserId = accessToken.Get("user_id"); tokens.UserName = userInfo.Get("name"); tokens.DisplayName = userInfo.Get("full_name"); tokens.FullName = userInfo.Get("full_name"); tokens.FirstName = userInfo.Get("first_name"); tokens.LastName = userInfo.Get("last_name"); var emails = userInfo.Object("contact").ArrayObjects("email_addresses").ConvertAll(x => new EmailAddresses { Type = x.Get("type"), Address = x.Get("address") }); var email = emails.FirstOrDefault(q => q.Type == "primary"); if (email != null) { tokens.Email = email.Address; } // Save session info incl. login state session.UserName = tokens.UserName; session.Email = tokens.Email; session.FirstName = tokens.FirstName; session.LastName = tokens.LastName; session.IsAuthenticated = true; authService.SaveSession(session, this.SessionExpiry); // Pass along this.OnAuthenticated(authService, session, tokens, authInfo.ToDictionary()); this.LoadUserAuthInfo((AuthUserSession)session, tokens, authInfo.ToDictionary()); // Has access! return authService.Redirect(this.CallbackUrl.AddHashParam("s", "1")); } catch (WebException webEx) { var statusCode = ((HttpWebResponse)webEx.Response).StatusCode; if (statusCode == HttpStatusCode.BadRequest) { return authService.Redirect(this.CallbackUrl.AddHashParam("f", "AccessTokenFailed")); } } // Unknown error, shouldn't get here. return authService.Redirect(this.CallbackUrl.AddHashParam("f", "Unknown")); }
public bool IsAuthorizedBySts(IAuthSession session, IOAuthTokens tokens, Auth request = null) { // TODO: For now... return(System.Threading.Thread.CurrentPrincipal != null && System.Threading.Thread.CurrentPrincipal.Identity != null && System.Threading.Thread.CurrentPrincipal.Identity.IsAuthenticated); }
public override object Authenticate(IServiceBase service, Auth request, IAuthSession session, IOAuthTokens tokens, OAuthAuthorizer oAuth) { var code = service.RequestContext.Get<IHttpRequest>().QueryString["code"]; var isPreAuthCallback = !code.IsNullOrEmpty(); if (!isPreAuthCallback) { var preAuthUrl = PreAuthUrl + "?client_id={0}&redirect_uri={1}&scope={2}" .Fmt(AppId, this.CallbackUrl.UrlEncode(), string.Join(",", Permissions)); return service.Redirect(preAuthUrl); } var accessTokenUrl = this.AccessTokenUrl + "?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}" .Fmt(AppId, this.CallbackUrl.UrlEncode(), AppSecret, code); try { var contents = accessTokenUrl.DownloadUrl(); var authInfo = HttpUtility.ParseQueryString(contents); tokens.AccessTokenSecret = authInfo["access_token"]; service.SaveSession(session); session.OnAuthenticated(service, tokens, authInfo.ToDictionary()); //Haz access! return service.Redirect(session.ReferrerUrl.AddHashParam("s", "1")); } catch (WebException we) { var statusCode = ((HttpWebResponse)we.Response).StatusCode; if (statusCode == HttpStatusCode.BadRequest) { return service.Redirect(session.ReferrerUrl.AddHashParam("f", "AccessTokenFailed")); } } //Shouldn't get here return service.Redirect(session.ReferrerUrl.AddHashParam("f", "Unknown")); }
public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request) { var tokens = Init(authService, ref session, request); //TODO: For now, later check for incoming URL to see from where it comes and decide... bool isAuthenticated = this.IsAuthorizedBySts(session, null, request); if (!isAuthenticated) { authService.SaveSession(session, SessionExpiry); return(AuthenticateWithSTS(authService, session, request)); } return(CompleteAuthentication(authService, session, request, tokens)); }
public virtual object Authenticate(IServiceBase service, Auth request, IAuthSession session, IOAuthTokens tokens, OAuthAuthorizer oAuth) { //Default oAuth logic based on Twitter's oAuth workflow if (!tokens.RequestToken.IsNullOrEmpty() && !request.oauth_token.IsNullOrEmpty()) { oAuth.RequestToken = tokens.RequestToken; oAuth.RequestTokenSecret = tokens.RequestTokenSecret; oAuth.AuthorizationToken = request.oauth_token; oAuth.AuthorizationVerifier = request.oauth_verifier; if (oAuth.AcquireAccessToken()) { tokens.AccessToken = oAuth.AccessToken; tokens.AccessTokenSecret = oAuth.AccessTokenSecret; session.OnAuthenticated(service, tokens, oAuth.AuthInfo); service.SaveSession(session); //Haz access! return service.Redirect(session.ReferrerUrl.AddHashParam("s", "1")); } //No Joy :( tokens.RequestToken = null; tokens.RequestTokenSecret = null; service.SaveSession(session); return service.Redirect(session.ReferrerUrl.AddHashParam("f", "AccessTokenFailed")); } if (oAuth.AcquireRequestToken()) { tokens.RequestToken = oAuth.RequestToken; tokens.RequestTokenSecret = oAuth.RequestTokenSecret; service.SaveSession(session); //Redirect to OAuth provider to approve access return service.Redirect(this.AuthorizeUrl .AddQueryParam("oauth_token", tokens.RequestToken) .AddQueryParam("oauth_callback", session.ReferrerUrl)); } return service.Redirect(session.ReferrerUrl.AddHashParam("f", "RequestTokenFailed")); }
/// <summary> /// Sets the CallbackUrl and session.ReferrerUrl if not set and initializes the session tokens for this AuthProvider /// </summary> /// <param name="authService"></param> /// <param name="session"></param> /// <param name="request"> </param> /// <returns></returns> protected IOAuthTokens Init(IServiceBase authService, ref IAuthSession session, Auth request) { if (request != null && !LoginMatchesSession(session, request.UserName)) { //authService.RemoveSession(); //session = authService.GetSession(); } var requestUri = authService.RequestContext.AbsoluteUri; if (this.CallbackUrl.IsNullOrEmpty()) this.CallbackUrl = requestUri; if (session.ReferrerUrl.IsNullOrEmpty()) session.ReferrerUrl = authService.RequestContext.GetHeader("Referer"); if (session.ReferrerUrl.IsNullOrEmpty() || session.ReferrerUrl.IndexOf("/auth", StringComparison.OrdinalIgnoreCase) >= 0) session.ReferrerUrl = this.RedirectUrl ?? ServiceStackHttpHandlerFactory.GetBaseUrl() ?? requestUri.Substring(0, requestUri.IndexOf("/", "https://".Length + 1)); var tokens = session.ProviderOAuthAccess.FirstOrDefault(x => x.Provider == Provider); if (tokens == null) session.ProviderOAuthAccess.Add(tokens = new OAuthTokens { Provider = Provider }); return tokens; }
public abstract object Authenticate(IServiceBase authService, IAuthSession session, Auth request);
public object Get(Auth request) { return(Post(request)); }
public override bool IsAuthorized(IAuthSession session, IOAuthTokens tokens, Auth request = null) { if (request != null) { if (!LoginMatchesSession(session, request.UserName)) return false; } // For OpenId, AccessTokenSecret is null/empty, but UserId is populated w/ authenticated url from openId providers return tokens != null && !string.IsNullOrEmpty(tokens.UserId); }
/// <summary> /// Public API entry point to authenticate via code /// </summary> /// <param name="request"></param> /// <returns>null; if already autenticated otherwise a populated instance of AuthResponse</returns> public AuthResponse Authenticate(Auth request) { //Remove HTML Content-Type to avoid auth providers issuing browser re-directs ((HttpRequestContext)this.RequestContext).ResponseContentType = ContentType.PlainText; var provider = request.provider ?? AuthProviders[0].Provider; var oAuthConfig = GetAuthProvider(provider); if (oAuthConfig == null) throw HttpError.NotFound("No configuration was added for OAuth provider '{0}'".Fmt(provider)); if (request.provider == LogoutAction) return oAuthConfig.Logout(this, request) as AuthResponse; var result = Authenticate(request, provider, this.GetSession(), oAuthConfig); var httpError = result as HttpError; if (httpError != null) throw httpError; return result as AuthResponse; }
public new AuthResponse Authenticate(ServiceStack.ServiceInterface.Auth.Auth request) { return(base.Authenticate(request)); }
public object Get(Auth request) { return Post(request); }
/// <summary> /// Sets the CallbackUrl and session.ReferrerUrl if not set and initializes the session tokens for this AuthProvider /// </summary> /// <param name="authService"></param> /// <param name="session"></param> /// <param name="request"> </param> /// <returns></returns> protected IOAuthTokens Init(IServiceBase authService, ref IAuthSession session, Auth request) { if (request != null && !LoginMatchesSession(session, request.UserName)) { //authService.RemoveSession(); //session = authService.GetSession(); } if (this.CallbackUrl.IsNullOrEmpty()) this.CallbackUrl = authService.RequestContext.AbsoluteUri; if (session.ReferrerUrl.IsNullOrEmpty()) session.ReferrerUrl = authService.RequestContext.GetHeader("Referer") ?? this.CallbackUrl; var tokens = session.ProviderOAuthAccess.FirstOrDefault(x => x.Provider == Provider); if (tokens == null) session.ProviderOAuthAccess.Add(tokens = new OAuthTokens { Provider = Provider }); return tokens; }
private object Authenticate(Auth request, string provider, IAuthSession session, IAuthProvider oAuthConfig) { object response = null; if (!oAuthConfig.IsAuthorized(session, session.GetOAuthTokens(provider), request)) { response = oAuthConfig.Authenticate(this, session, request); } return response; }
public void Options(Auth request) { }
public override object Logout(IServiceBase service, Auth request) { return base.Logout(service, request); }
private object CompleteAuthentication(IServiceBase authService, IAuthSession session, Auth request, IOAuthTokens tokens) { try { NameValueCollection claims = ExtractClaims(); // TODO: Probably recheck claims before making IsAuthenticaed = true... session.IsAuthenticated = true; authService.SaveSession(session, SessionExpiry); OnAuthenticated(authService, session, tokens, claims.ToDictionary()); //Haz access! return(authService.Redirect(session.ReferrerUrl.AddHashParam("s", "1"))); } catch (WebException we) { var statusCode = ((HttpWebResponse)we.Response).StatusCode; if (statusCode == HttpStatusCode.BadRequest) { return(authService.Redirect(session.ReferrerUrl.AddHashParam("f", "AccessTokenFailed"))); } } catch (Exception ex) { return(authService.Redirect(session.ReferrerUrl.AddHashParam("f", "Unknown Error"))); } return(null); }
public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request) { //new CredentialsAuthValidator().ValidateAndThrow(request); return(Authenticate(authService, session, request.UserName, request.Password)); }
public virtual object Get(Auth request) { return(Post(request)); }
public abstract bool IsAuthorized(IAuthSession session, IOAuthTokens tokens, Auth request = null);
public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request) { var tokens = Init(authService, ref session, request); var httpReq = authService.RequestContext.Get<IHttpRequest>(); var httpMethod = httpReq.HttpMethod; if (httpMethod == HttpMethods.Post) { var openIdUrl = httpReq.GetParam("OpenIdUrl") ?? base.AuthRealm; if (openIdUrl.IsNullOrEmpty()) throw new ArgumentException("'OpenIdUrl' is required a required field"); try { using (var openid = new OpenIdRelyingParty()) { var openIdRequest = openid.CreateRequest(openIdUrl); AddAttributeExchangeExtensions(openIdRequest); // This is where you would add any OpenID extensions you wanted // to include in the authentication request. openIdRequest.AddExtension(CreateClaimsRequest(httpReq)); // Send your visitor to their Provider for authentication. var openIdResponse = openIdRequest.RedirectingResponse; var contentType = openIdResponse.Headers[HttpHeaders.ContentType]; var httpResult = new HttpResult(openIdResponse.ResponseStream, contentType) { StatusCode = openIdResponse.Status, StatusDescription = "Moved Temporarily", }; foreach (string header in openIdResponse.Headers) { httpResult.Headers[header] = openIdResponse.Headers[header]; } // Save the current session to keep the ReferrerUrl available (similar to Facebook provider) authService.SaveSession(session, SessionExpiry); return httpResult; } } catch (ProtocolException ex) { Log.Error("Failed to login to {0}".Fmt(openIdUrl), ex); return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "Unknown")); } } if (httpMethod == HttpMethods.Get) { using (var openid = new OpenIdRelyingParty()) { var response = openid.GetResponse(); if (response != null) { switch (response.Status) { case AuthenticationStatus.Authenticated: var authInfo = CreateAuthInfo(response); // Use FormsAuthentication to tell ASP.NET that the user is now logged in, // with the OpenID Claimed Identifier as their username. session.IsAuthenticated = true; authService.SaveSession(session, SessionExpiry); OnAuthenticated(authService, session, tokens, authInfo); //Haz access! return authService.Redirect(session.ReferrerUrl.AddHashParam("s", "1")); case AuthenticationStatus.Canceled: return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "ProviderCancelled")); case AuthenticationStatus.Failed: return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "Unknown")); } } } } //Shouldn't get here return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "Unknown")); }