예제 #1
0
        protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary <string, string> authInfo)
        {
            if (authInfo.ContainsKey("user_id"))
            {
                tokens.UserId = authInfo.GetValueOrDefault("user_id");
            }

            if (authInfo.ContainsKey("screen_name"))
            {
                tokens.UserName = authInfo.GetValueOrDefault("screen_name");
            }

            try
            {
                if (tokens.UserId != null)
                {
                    var json = AuthHttpGateway.DownloadTwitterUserInfo(tokens.UserId);
                    var objs = JsonObject.ParseArray(json);
                    if (objs.Count > 0)
                    {
                        var obj = objs[0];
                        tokens.DisplayName = obj.Get("name");
                    }
                }

                LoadUserOAuthProvider(userSession, tokens);
            }
            catch (Exception ex)
            {
                Log.Error("Could not retrieve twitter user info for '{0}'".Fmt(userSession.TwitterUserId), ex);
            }
        }
예제 #2
0
        protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary <string, string> authInfo)
        {
            try
            {
                tokens.UserId      = authInfo.Get("id");
                tokens.UserName    = authInfo.Get("email") ?? authInfo.Get("id") ?? authInfo.Get("username");
                tokens.DisplayName = authInfo.Get("name");
                tokens.FirstName   = authInfo.Get("given_name");
                tokens.LastName    = authInfo.Get("family_name");
                tokens.Email       = authInfo.Get("email");

                var json = AuthHttpGateway.DownloadGoogleUserInfo(tokens.AccessTokenSecret);
                var obj  = (Dictionary <string, object>)JSON.parse(json);

                if (obj.TryGetValue("picture", out var oProfileUrl) && oProfileUrl is string profileUrl)
                {
                    tokens.Items[AuthMetadataProvider.ProfileUrlKey] = profileUrl.SanitizeOAuthUrl();
                }
            }
            catch (Exception ex)
            {
                Log.Error($"Could not retrieve google user info for '{tokens.DisplayName}'", ex);
            }

            LoadUserOAuthProvider(userSession, tokens);
        }
예제 #3
0
        protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary <string, string> authInfo)
        {
            try
            {
                tokens.UserId      = authInfo.Get("id");
                tokens.UserName    = authInfo.Get("id") ?? authInfo.Get("username");
                tokens.DisplayName = authInfo.Get("name");
                tokens.FirstName   = authInfo.Get("first_name");
                tokens.LastName    = authInfo.Get("last_name");
                tokens.Email       = authInfo.Get("email");

                var json    = AuthHttpGateway.DownloadFacebookUserInfo(tokens.AccessTokenSecret, "picture");
                var obj     = JsonObject.Parse(json);
                var picture = obj.Object("picture");
                var data    = picture?.Object("data");
                if (data != null)
                {
                    if (data.TryGetValue("url", out var profileUrl))
                    {
                        tokens.Items[AuthMetadataProvider.ProfileUrlKey] = profileUrl.SanitizeOAuthUrl();
                    }
                }
                userSession.UserAuthName = tokens.Email ?? tokens.UserName;
            }
            catch (Exception ex)
            {
                Log.Error($"Could not retrieve facebook user info for '{tokens.DisplayName}'", ex);
            }

            LoadUserOAuthProvider(userSession, tokens);
        }
예제 #4
0
        protected virtual async Task <object> AuthenticateWithAccessTokenAsync(IServiceBase authService, IAuthSession session, IAuthTokens tokens, string accessToken, CancellationToken token = default)
        {
            tokens.AccessTokenSecret = accessToken;

            var json     = AuthHttpGateway.DownloadFacebookUserInfo(accessToken, Fields);
            var authInfo = JsonObject.Parse(json);

            session.IsAuthenticated = true;

            return(await OnAuthenticatedAsync(authService, session, tokens, authInfo, token).ConfigAwait());
        }
예제 #5
0
        protected virtual object AuthenticateWithAccessToken(IServiceBase authService, IAuthSession session, IAuthTokens tokens, string accessToken)
        {
            tokens.AccessTokenSecret = accessToken;

            var json     = AuthHttpGateway.DownloadGithubUserInfo(accessToken);
            var authInfo = JsonObject.Parse(json);

            session.IsAuthenticated = true;

            return(OnAuthenticated(authService, session, tokens, authInfo));
        }
예제 #6
0
        protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary <string, string> authInfo)
        {
            if (authInfo.ContainsKey("user_id"))
            {
                tokens.UserId = authInfo.GetValueOrDefault("user_id");
            }

            if (authInfo.ContainsKey("screen_name"))
            {
                tokens.UserName = authInfo.GetValueOrDefault("screen_name");
            }

            var userId = tokens.UserId ?? userSession.TwitterUserId;

            try
            {
                if (userId != null)
                {
                    var json = AuthHttpGateway.DownloadTwitterUserInfo(
                        ConsumerKey, ConsumerSecret,
                        tokens.AccessToken, tokens.AccessTokenSecret,
                        userId);

                    var objs = JsonObject.ParseArray(json);
                    if (objs.Count > 0)
                    {
                        ParseJsonObject(objs[0], tokens, authInfo);
                    }
                }
                else if (tokens.AccessToken != null && tokens.AccessTokenSecret != null)
                {
                    var json = AuthHttpGateway.VerifyTwitterCredentials(
                        ConsumerKey, ConsumerSecret,
                        tokens.AccessToken, tokens.AccessTokenSecret);

                    var obj = JsonObject.Parse(json);
                    ParseJsonObject(obj, tokens, authInfo);
                }
            }
            catch (Exception ex)
            {
                if (userId != null)
                {
                    Log.Error($"Could not retrieve twitter user info for '{userId}'", ex);
                }

                throw;
            }

            LoadUserOAuthProvider(userSession, tokens);
        }
예제 #7
0
        protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary <string, string> authInfo)
        {
            if (authInfo.ContainsKey("user_id"))
            {
                tokens.UserId = authInfo.GetValueOrDefault("user_id");
            }

            if (authInfo.ContainsKey("screen_name"))
            {
                tokens.UserName = authInfo.GetValueOrDefault("screen_name");
            }

            try
            {
                if (tokens.UserId != null)
                {
                    var oauthToken = new OAuthAccessToken
                    {
                        OAuthProvider     = this,
                        AccessToken       = tokens.AccessToken,
                        AccessTokenSecret = tokens.AccessTokenSecret,
                    };
                    var json = AuthHttpGateway.DownloadTwitterUserInfo(oauthToken, tokens.UserId);
                    var objs = JsonObject.ParseArray(json);
                    if (objs.Count > 0)
                    {
                        var obj = objs[0];
                        tokens.DisplayName = obj.Get("name");

                        string profileUrl;
                        if (obj.TryGetValue("profile_image_url", out profileUrl))
                        {
                            tokens.Items[AuthMetadataProvider.ProfileUrlKey] = profileUrl;
                        }

                        if (SaveExtendedUserInfo)
                        {
                            obj.Each(x => authInfo[x.Key] = x.Value);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("Could not retrieve twitter user info for '{0}'".Fmt(userSession.TwitterUserId), ex);
            }

            LoadUserOAuthProvider(userSession, tokens);
        }
예제 #8
0
        protected override async Task LoadUserAuthInfoAsync(AuthUserSession userSession, IAuthTokens tokens, Dictionary <string, string> authInfo, CancellationToken token = default)
        {
            try
            {
                tokens.UserId      = authInfo.Get("id");
                tokens.UserName    = authInfo.Get("login");
                tokens.DisplayName = authInfo.Get("name");
                tokens.Email       = authInfo.Get("email");
                tokens.Company     = authInfo.Get("company");
                tokens.Country     = authInfo.Get("country");

                if (authInfo.TryGetValue("avatar_url", out var profileUrl))
                {
                    tokens.Items[AuthMetadataProvider.ProfileUrlKey] = profileUrl;

                    if (string.IsNullOrEmpty(userSession.ProfileUrl))
                    {
                        userSession.ProfileUrl = profileUrl.SanitizeOAuthUrl();
                    }
                }

                if (string.IsNullOrEmpty(tokens.Email))
                {
                    var json = await AuthHttpGateway.DownloadGithubUserEmailsInfoAsync(tokens.AccessTokenSecret, token).ConfigAwait();

                    var objs = JsonArrayObjects.Parse(json);
                    foreach (var obj in objs)
                    {
                        if (obj.Get <bool>("primary"))
                        {
                            tokens.Email = obj.Get("email");
                            if (obj.Get <bool>("verified"))
                            {
                                tokens.Items["email_verified"] = "true";
                            }
                            break;
                        }
                    }
                }
                userSession.UserAuthName = tokens.UserName ?? tokens.Email;
            }
            catch (Exception ex)
            {
                Log.Error($"Could not retrieve github user info for '{tokens.DisplayName}'", ex);
            }

            LoadUserOAuthProvider(userSession, tokens);
        }
예제 #9
0
        protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary <string, string> authInfo)
        {
            try
            {
                tokens.UserId      = authInfo.Get("id");
                tokens.UserName    = authInfo.Get("login");
                tokens.DisplayName = authInfo.Get("name");
                tokens.Email       = authInfo.Get("email");
                tokens.Company     = authInfo.Get("company");
                tokens.Country     = authInfo.Get("country");

                string profileUrl;
                if (authInfo.TryGetValue("avatar_url", out profileUrl))
                {
                    tokens.Items[AuthMetadataProvider.ProfileUrlKey] = profileUrl;
                }

                if (tokens.Email == null)
                {
                    var json = AuthHttpGateway.DownloadGithubUserEmailsInfo(tokens.AccessTokenSecret);
                    var objs = JsonArrayObjects.Parse(json);
                    foreach (var obj in objs)
                    {
                        if (obj.Get <bool>("primary"))
                        {
                            tokens.Email = obj.Get("email");
                            if (obj.Get <bool>("verified"))
                            {
                                tokens.Items["email_veriried"] = "true";
                            }
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error($"Could not retrieve github user info for '{tokens.DisplayName}'", ex);
            }

            LoadUserOAuthProvider(userSession, tokens);
        }
예제 #10
0
        protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, System.Collections.Generic.Dictionary <string, string> authInfo)
        {
            try
            {
                var json = AuthHttpGateway.DownloadFacebookUserInfo(tokens.AccessTokenSecret);
                var obj  = JsonObject.Parse(json);
                tokens.UserId      = obj.Get("id");
                tokens.UserName    = obj.Get("username");
                tokens.DisplayName = obj.Get("name");
                tokens.FirstName   = obj.Get("first_name");
                tokens.LastName    = obj.Get("last_name");
                tokens.Email       = obj.Get("email");

                LoadUserOAuthProvider(userSession, tokens);
            }
            catch (Exception ex)
            {
                Log.Error("Could not retrieve facebook user info for '{0}'".Fmt(tokens.DisplayName), ex);
            }
        }
        /// <summary>
        /// Load the UserAuth info into the session.
        /// </summary>
        /// <param name="userSession">
        /// The User session.
        /// </param>
        /// <param name="tokens">
        /// The OAuth tokens.
        /// </param>
        /// <param name="authInfo">
        /// The auth info.
        /// </param>
        protected override async Task LoadUserAuthInfoAsync(AuthUserSession userSession, IAuthTokens tokens, Dictionary <string, string> authInfo, CancellationToken token = default)
        {
            try
            {
                var contents = await AuthHttpGateway.DownloadYammerUserInfoAsync(tokens.UserId).ConfigAwait();

                var obj = JsonObject.Parse(contents);

                tokens.UserId      = obj.Get("id");
                tokens.UserName    = obj.Get("name");
                tokens.DisplayName = obj.Get("full_name");
                tokens.FullName    = obj.Get("full_name");
                tokens.FirstName   = obj.Get("first_name");
                tokens.LastName    = obj.Get("last_name");

                var emails = obj.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;
                }

                if (SaveExtendedUserInfo)
                {
                    obj.Each(x => authInfo[x.Key] = x.Value);
                }
                userSession.UserAuthName = tokens.Email;
            }
            catch (Exception ex)
            {
                Log.Error($"Could not retrieve Yammer user info for '{tokens.DisplayName}'", ex);
            }

            this.LoadUserOAuthProvider(userSession, tokens);
        }
예제 #12
0
        protected override async Task LoadUserAuthInfoAsync(AuthUserSession userSession, IAuthTokens tokens, Dictionary <string, string> authInfo, CancellationToken token = default)
        {
            try
            {
                tokens.UserId      = authInfo.Get("id");
                tokens.UserName    = authInfo.Get("id") ?? authInfo.Get("username");
                tokens.DisplayName = authInfo.Get("name");
                tokens.FirstName   = authInfo.Get("first_name");
                tokens.LastName    = authInfo.Get("last_name");
                tokens.Email       = authInfo.Get("email");

                if (RetrieveUserPicture)
                {
                    var json = await AuthHttpGateway.DownloadFacebookUserInfoAsync(tokens.AccessTokenSecret, new[] { "picture" }, token).ConfigAwait();

                    var obj     = JsonObject.Parse(json);
                    var picture = obj.Object("picture");
                    var data    = picture?.Object("data");
                    if (data != null)
                    {
                        if (data.TryGetValue("url", out var profileUrl))
                        {
                            tokens.Items[AuthMetadataProvider.ProfileUrlKey] = profileUrl.SanitizeOAuthUrl();

                            if (string.IsNullOrEmpty(userSession.ProfileUrl))
                            {
                                userSession.ProfileUrl = profileUrl.SanitizeOAuthUrl();
                            }
                        }
                    }
                }

                userSession.UserAuthName = tokens.Email;
            }
            catch (Exception ex)
            {
                Log.Error($"Could not retrieve facebook user info for '{tokens.DisplayName}'", ex);
            }

            LoadUserOAuthProvider(userSession, tokens);
        }
예제 #13
0
        protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, System.Collections.Generic.Dictionary <string, string> authInfo)
        {
            try
            {
                var json = AuthHttpGateway.DownloadFacebookUserInfo(tokens.AccessTokenSecret);
                var obj  = JsonObject.Parse(json);
                tokens.UserId      = obj.Get("id");
                tokens.UserName    = obj.Get("username");
                tokens.DisplayName = obj.Get("name");
                tokens.FirstName   = obj.Get("first_name");
                tokens.LastName    = obj.Get("last_name");
                tokens.Email       = obj.Get("email");

                if (SaveExtendedUserInfo)
                {
                    obj.Each(x => authInfo[x.Key] = x.Value);
                }

                json = AuthHttpGateway.DownloadFacebookUserInfo(tokens.AccessTokenSecret, "picture");
                obj  = JsonObject.Parse(json);
                var picture = obj.Object("picture");
                var data    = picture != null?picture.Object("data") : null;

                if (data != null)
                {
                    string profileUrl;
                    if (data.TryGetValue("url", out profileUrl))
                    {
                        tokens.Items[AuthMetadataProvider.ProfileUrlKey] = profileUrl;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("Could not retrieve facebook user info for '{0}'".Fmt(tokens.DisplayName), ex);
            }

            LoadUserOAuthProvider(userSession, tokens);
        }
예제 #14
0
        /// <summary>
        /// Load the UserAuth info into the session.
        /// </summary>
        /// <param name="userSession">
        /// The User session.
        /// </param>
        /// <param name="tokens">
        /// The OAuth tokens.
        /// </param>
        /// <param name="authInfo">
        /// The auth info.
        /// </param>
        protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary <string, string> authInfo)
        {
            try
            {
                var contents = AuthHttpGateway.DownloadYammerUserInfo(tokens.UserId);

                var authObj = JsonObject.Parse(contents);

                tokens.UserId      = authObj.Get("id");
                tokens.UserName    = authObj.Get("name");
                tokens.DisplayName = authObj.Get("full_name");
                tokens.FullName    = authObj.Get("full_name");
                tokens.FirstName   = authObj.Get("first_name");
                tokens.LastName    = authObj.Get("last_name");

                var emails = authObj.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;
                }

                // Pass along
                this.LoadUserOAuthProvider(userSession, tokens);
            }
            catch (Exception ex)
            {
                Log.Error("Could not retrieve Yammer user info for '{0}'".Fmt(tokens.DisplayName), ex);
            }
        }
예제 #15
0
        public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request)
        {
            var tokens = Init(authService, ref session, request);

            //Transferring AccessToken/Secret from Mobile/Desktop App to Server
            if (request.AccessToken != null && request.AccessTokenSecret != null)
            {
                tokens.AccessToken       = request.AccessToken;
                tokens.AccessTokenSecret = request.AccessTokenSecret;

                var validToken = AuthHttpGateway.VerifyTwitterAccessToken(
                    ConsumerKey, ConsumerSecret,
                    tokens.AccessToken, tokens.AccessTokenSecret,
                    out var userId,
                    out var email);

                if (!validToken)
                {
                    return(HttpError.Unauthorized("AccessToken is invalid"));
                }

                if (!string.IsNullOrEmpty(request.UserName) && userId != request.UserName)
                {
                    return(HttpError.Unauthorized("AccessToken does not match UserId: " + request.UserName));
                }

                tokens.UserId           = userId;
                session.IsAuthenticated = true;

                var failedResult = OnAuthenticated(authService, session, tokens, new Dictionary <string, string>());
                var isHtml       = authService.Request.IsHtml();
                if (failedResult != null)
                {
                    return(ConvertToClientError(failedResult, isHtml));
                }

                return(isHtml
                    ? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1")))
                    : null); //return default AuthenticateResponse
            }

            //Default OAuth logic based on Twitter's OAuth workflow
            if (!tokens.RequestTokenSecret.IsNullOrEmpty() && !request.oauth_token.IsNullOrEmpty())
            {
                if (OAuthUtils.AcquireAccessToken(tokens.RequestTokenSecret, request.oauth_token, request.oauth_verifier))
                {
                    session.IsAuthenticated  = true;
                    tokens.AccessToken       = OAuthUtils.AccessToken;
                    tokens.AccessTokenSecret = OAuthUtils.AccessTokenSecret;

                    return(OnAuthenticated(authService, session, tokens, OAuthUtils.AuthInfo)
                           ?? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1")))); //Haz Access
                }

                //No Joy :(
                tokens.RequestToken       = null;
                tokens.RequestTokenSecret = null;
                this.SaveSession(authService, session, SessionExpiry);
                return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "AccessTokenFailed"))));
            }
            if (OAuthUtils.AcquireRequestToken())
            {
                tokens.RequestToken       = OAuthUtils.RequestToken;
                tokens.RequestTokenSecret = OAuthUtils.RequestTokenSecret;
                this.SaveSession(authService, session, SessionExpiry);

                //Redirect to OAuth provider to approve access
                return(authService.Redirect(AccessTokenUrlFilter(this, this.AuthorizeUrl
                                                                 .AddQueryParam("oauth_token", tokens.RequestToken)
                                                                 .AddQueryParam("oauth_callback", session.ReferrerUrl)
                                                                 .AddQueryParam(Keywords.State, session.Id) // doesn't support state param atm, but it's here when it does
                                                                 )));
            }

            return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "RequestTokenFailed"))));
        }
예제 #16
0
        protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary <string, string> authInfo)
        {
            if (authInfo.ContainsKey("user_id"))
            {
                tokens.UserId = authInfo.GetValueOrDefault("user_id");
            }

            if (authInfo.ContainsKey("screen_name"))
            {
                tokens.UserName = authInfo.GetValueOrDefault("screen_name");
            }

            var userId = tokens.UserId ?? userSession.TwitterUserId;

            try
            {
                if (userId != null)
                {
                    var json = AuthHttpGateway.DownloadTwitterUserInfo(
                        ConsumerKey, ConsumerSecret,
                        tokens.AccessToken, tokens.AccessTokenSecret,
                        userId);

                    var objs = JsonObject.ParseArray(json);
                    if (objs.Count > 0)
                    {
                        var obj = objs[0];

                        tokens.DisplayName = obj.Get("name");

                        var userName = obj.Get("screen_name");
                        if (!string.IsNullOrEmpty(userName))
                        {
                            tokens.UserName = userName;
                        }

                        var email = obj.Get("email");
                        if (!string.IsNullOrEmpty(email))
                        {
                            tokens.Email = email;
                        }
                        else if (RetrieveEmail)
                        {
                            try
                            {
                                AuthHttpGateway.VerifyTwitterAccessToken(
                                    ConsumerKey, ConsumerSecret,
                                    tokens.AccessToken, tokens.AccessTokenSecret,
                                    out userId, out email);

                                tokens.Email = email;
                            }
                            catch (Exception ex)
                            {
                                Log.Warn($"Could not retrieve Twitter Email", ex);
                            }
                        }

                        if (obj.TryGetValue("profile_image_url", out var profileUrl))
                        {
                            tokens.Items[AuthMetadataProvider.ProfileUrlKey] = profileUrl;

                            if (string.IsNullOrEmpty(userSession.ProfileUrl))
                            {
                                userSession.ProfileUrl = profileUrl.SanitizeOAuthUrl();
                            }
                        }

                        if (SaveExtendedUserInfo)
                        {
                            obj.Each(x => authInfo[x.Key] = x.Value);
                        }
                    }
                }
                userSession.UserAuthName = tokens.UserName ?? tokens.Email;
            }
            catch (Exception ex)
            {
                if (userId != null)
                {
                    Log.Error($"Could not retrieve twitter user info for '{userId}'", ex);
                }

                throw;
            }

            LoadUserOAuthProvider(userSession, tokens);
        }
예제 #17
0
        public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request)
        {
            var tokens = Init(authService, ref session, request);

            //Transferring AccessToken/Secret from Mobile/Desktop App to Server
            if (request?.AccessToken != null)
            {
                if (!AuthHttpGateway.VerifyFacebookAccessToken(AppId, request.AccessToken))
                {
                    return(HttpError.Unauthorized("AccessToken is not for App: " + AppId));
                }

                var isHtml       = authService.Request.IsHtml();
                var failedResult = AuthenticateWithAccessToken(authService, session, tokens, request.AccessToken);
                if (failedResult != null)
                {
                    return(ConvertToClientError(failedResult, isHtml));
                }

                return(isHtml
                    ? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1")))
                    : null); //return default AuthenticateResponse
            }

            var httpRequest = authService.Request;
            var error       = httpRequest.QueryString["error_reason"]
                              ?? httpRequest.QueryString["error"]
                              ?? httpRequest.QueryString["error_code"]
                              ?? httpRequest.QueryString["error_description"];

            var hasError = !error.IsNullOrEmpty();

            if (hasError)
            {
                Log.Error($"Facebook error callback. {httpRequest.QueryString}");
                return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", error))));
            }

            var code = httpRequest.QueryString[Keywords.Code];
            var isPreAuthCallback = !code.IsNullOrEmpty();

            if (!isPreAuthCallback)
            {
                var preAuthUrl = $"{PreAuthUrl}?client_id={AppId}&redirect_uri={this.CallbackUrl.UrlEncode()}&scope={string.Join(",", Permissions)}&{Keywords.State}={session.Id}";

                this.SaveSession(authService, session, SessionExpiry);
                return(authService.Redirect(PreAuthUrlFilter(this, preAuthUrl)));
            }

            try
            {
                var accessTokenUrl = $"{AccessTokenUrl}?client_id={AppId}&redirect_uri={this.CallbackUrl.UrlEncode()}&client_secret={AppSecret}&code={code}";
                var contents       = AccessTokenUrlFilter(this, accessTokenUrl).GetJsonFromUrl();
                var authInfo       = JsonObject.Parse(contents);

                var accessToken = authInfo["access_token"];

                return(AuthenticateWithAccessToken(authService, session, tokens, accessToken)
                       ?? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1")))); //Haz Access!
            }
            catch (WebException we)
            {
                var statusCode = ((HttpWebResponse)we.Response).StatusCode;
                if (statusCode == HttpStatusCode.BadRequest)
                {
                    return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "AccessTokenFailed"))));
                }
            }

            //Shouldn't get here
            return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "Unknown"))));
        }