Пример #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("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 = 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_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);
        }
        protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary <string, string> authInfo)
        {
            try
            {
                //sig = md5( request_params_composed_string + md5(access_token + application_secret_key)  )

                string innerSignature = Encoding.UTF8.GetBytes(tokens.AccessTokenSecret + ConsumerSecret).ToMd5Hash();
                string signature      = Encoding.UTF8.GetBytes($"application_key={PublicKey}" + innerSignature).ToMd5Hash();

                string payload = $"access_token={tokens.AccessTokenSecret}&sig={signature}&application_key={PublicKey}";

                string json = "http://api.odnoklassniki.ru/api/users/getCurrentUser".PostToUrl(payload, "*/*", RequestFilter);

                JsonObject obj = JsonObject.Parse(json);

                if (!obj.Get("error").IsNullOrEmpty())
                {
                    Logger.Error($"Could not retrieve Odnoklassniki user info for '{tokens.DisplayName}', Response:{json}");
                    return;
                }

                //response fields info: http://apiok.ru/wiki/display/api/users.getCurrentUser+ru
                var location = JsonObject.Parse(obj.GetUnescaped("location"));

                tokens.UserId       = obj.Get("uid");
                tokens.DisplayName  = obj.Get("name");
                tokens.FirstName    = obj.Get("first_name");
                tokens.LastName     = obj.Get("last_name");
                tokens.BirthDateRaw = obj.Get("birthday");
                tokens.Language     = obj.Get("locale");
                tokens.Country      = location.Get("countryCode");
                tokens.City         = location.Get("city");
                tokens.Gender       = obj.Get("gender");

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

            LoadUserOAuthProvider(userSession, tokens);
        }
Пример #4
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 '{userSession.TwitterUserId}'", ex);
            }

            LoadUserOAuthProvider(userSession, tokens);
        }
Пример #5
0
        protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary <string, string> authInfo)
        {
            try
            {
                tokens.UserId            = authInfo.Get("user_id");
                tokens.UserName          = authInfo.Get("email") ?? authInfo.Get("username") ?? tokens.UserId;
                tokens.DisplayName       = authInfo.Get("name");
                tokens.FirstName         = authInfo.Get("first_name");
                tokens.LastName          = authInfo.Get("last_name");
                tokens.Email             = authInfo.Get("email");
                userSession.UserAuthName = tokens.Email;
            }
            catch (Exception ex)
            {
                Log.Error($"Could not retrieve '{Provider}' profile user info for '{tokens.DisplayName}'", ex);
            }

            LoadUserOAuthProvider(userSession, tokens);
        }
Пример #6
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);
            }
        }
Пример #7
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);
            }
        }
Пример #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("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);
        }
        /// <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);
        }
Пример #10
0
        protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary <string, string> authInfo)
        {
            try
            {
                var json = "https://api.github.com/user?access_token={0}"
                           .Fmt(tokens.AccessTokenSecret).GetStringFromUrl("*/*", UserRequestFilter);
                var obj = JsonObject.Parse(json);

                tokens.UserId      = obj.Get("id");
                tokens.UserName    = obj.Get("login");
                tokens.DisplayName = obj.Get("name");
                tokens.Email       = obj.Get("email");
                tokens.Company     = obj.Get("company");
                tokens.Country     = obj.Get("country");

                LoadUserOAuthProvider(userSession, tokens);
            }
            catch (Exception ex)
            {
                Log.Error("Could not retrieve github user info for '{0}'".Fmt(tokens.DisplayName), ex);
            }
        }
Пример #11
0
        protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary <string, string> authInfo)
        {
            try
            {
                string     json = "https://login.yandex.ru/info?format=json&oauth_token={0}".Fmt(tokens.AccessTokenSecret).GetJsonFromUrl();
                JsonObject obj  = JsonObject.Parse(json);

                tokens.UserId       = obj.Get("id");
                tokens.UserName     = obj.Get("display_name");
                tokens.DisplayName  = obj.Get("real_name");
                tokens.FirstName    = obj.Get("first_name");
                tokens.LastName     = obj.Get("last_name");
                tokens.Email        = obj.Get("default_email");
                tokens.BirthDateRaw = obj.Get("birthday");

                LoadUserOAuthProvider(userSession, tokens);
            }
            catch (Exception ex)
            {
                Log.Error("Could not retrieve Yandex user info for '{0}'".Fmt(tokens.DisplayName), ex);
            }
        }
Пример #12
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);
        }
Пример #13
0
        protected override async Task LoadUserAuthInfoAsync(AuthUserSession userSession, IAuthTokens tokens, Dictionary <string, string> authInfo, CancellationToken token = default)
        {
            try
            {
                string     json = await $"https://login.yandex.ru/info?format=json&oauth_token={tokens.AccessTokenSecret}".GetJsonFromUrlAsync().ConfigAwait();
                JsonObject obj  = JsonObject.Parse(json);

                tokens.UserId            = obj.Get("id");
                tokens.UserName          = obj.Get("display_name");
                tokens.DisplayName       = obj.Get("real_name");
                tokens.FirstName         = obj.Get("first_name");
                tokens.LastName          = obj.Get("last_name");
                tokens.Email             = obj.Get("default_email");
                tokens.BirthDateRaw      = obj.Get("birthday");
                userSession.UserAuthName = tokens.Email;

                LoadUserOAuthProvider(userSession, tokens);
            }
            catch (Exception ex)
            {
                Log.Error($"Could not retrieve Yandex user info for '{tokens.DisplayName}'", ex);
            }
        }
Пример #14
0
        protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary <string, string> authInfo)
        {
            try
            {
                string json = "https://api.vk.com/method/users.get?user_ids={0}&fields=screen_name,bdate,city,country,timezone&oauth_token={0}"
                              .Fmt(tokens.UserId, tokens.AccessTokenSecret).GetJsonFromUrl();

                JsonObject obj = json.ArrayObjects()[0].GetUnescaped("response").ArrayObjects()[0];

                tokens.UserName     = obj.Get("screen_name");
                tokens.DisplayName  = obj.Get("screen_name");
                tokens.FirstName    = obj.Get("first_name");
                tokens.LastName     = obj.Get("last_name");
                tokens.BirthDateRaw = obj.Get("bdate");
                tokens.TimeZone     = obj.Get("timezone");

                LoadUserOAuthProvider(userSession, tokens);
            }
            catch (Exception ex)
            {
                Log.Error("Could not retrieve VK user info for '{0}'".Fmt(tokens.DisplayName), ex);
            }
        }
Пример #15
0
        protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary <string, string> authInfo)
        {
            try {
                if (!tokens.AccessToken.IsNullOrEmpty() && !tokens.AccessTokenSecret.IsNullOrEmpty())
                {
                    tokens.UserName     = authInfo.Get("screen_name");
                    tokens.DisplayName  = authInfo.Get("screen_name");
                    tokens.FirstName    = authInfo.Get("first_name");
                    tokens.LastName     = authInfo.Get("last_name");
                    tokens.BirthDateRaw = authInfo.Get("bdate");
                    tokens.TimeZone     = authInfo.Get("timezone");
                }
                else
                {
                    string json = "https://api.vk.com/method/users.get?user_ids={0}&fields=screen_name,bdate,city,country,timezone&oauth_token={0}"
                                  .Fmt(tokens.UserId, tokens.AccessTokenSecret).GetJsonFromUrl();

                    var obj = json.ArrayObjects()[0].GetUnescaped("response").ArrayObjects()[0];

                    tokens.UserName     = obj.Get("screen_name");
                    tokens.DisplayName  = obj.Get("screen_name");
                    tokens.FirstName    = obj.Get("first_name");
                    tokens.LastName     = obj.Get("last_name");
                    tokens.BirthDateRaw = obj.Get("bdate");
                    tokens.TimeZone     = obj.Get("timezone");

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

            LoadUserOAuthProvider(userSession, tokens);
        }
Пример #16
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);
            }
        }
        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);
        }
        public void ShouldUseLoginHintWhenUserNameKnown()
        {
            using (TestAppHost())
            {
                Subject.ClientId = "c1";
                Subject.DomainHint = "domain.hint";
                var tokens = new AuthTokens
                {
                    Provider = "aad",
                    UserName = "******"
                };
                var session = new AuthUserSession();
                session.ProviderOAuthAccess.Add(tokens);

                var response = Subject.Authenticate(MockAuthService().Object, session, new Authenticate());

                var result = (IHttpResult)response;
                var codeRequest = new Uri(result.Headers["Location"]);
                var query = PclExportClient.Instance.ParseQueryString(codeRequest.Query);
                query["login_hint"].Should().Be(tokens.UserName);
            }
        }
        public void ShouldRequestToken()
        {
            // When an application sends a GET request for an authorization code, Azure AD sends a response to the
            // value of the redirect_uri parameter in the request. The response includes the following parameters:
            //      [admin_consent], code, session_state, state
            using (TestAppHost())
            {
                Subject.ClientId = "2d4d11a2-f814-46a7-890a-274a72a7309e";
                Subject.CallbackUrl = "http://localhost/myapp/";
                var request = new MockHttpRequest("myapp", "GET", "text", "/myapp", new NameValueCollection {
                    {"code", "AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdgfSTLEMPGYuNHSUYBrqqf_ZT_p5uEAEJJ_nZ3UmphWygRNy2C3jJ239gV_DBnZ2syeg95Ki-374WHUP-i3yIhv5i-7KU2CEoPXwURQp6IVYMw-DjAOzn7C3JCu5wpngXmbZKtJdWmiBzHpcO2aICJPu1KvJrDLDP20chJBXzVYJtkfjviLNNW7l7Y3ydcHDsBRKZc3GuMQanmcghXPyoDg41g8XbwPudVh7uCmUponBQpIhbuffFP_tbV8SNzsPoFz9CLpBCZagJVXeqWoYMPe2dSsPiLO9Alf_YIe5zpi-zY4C3aLw5g9at35eZTfNd0gBRpR5ojkMIcZZ6IgAA"},
                    {"session_state", "7B29111D-C220-4263-99AB-6F6E135D75EF"},
                    {"state", "D79E5777-702E-4260-9A62-37F75FF22CCE" }
                }, Stream.Null, null);
                var mockAuthService = MockAuthService(request);
                using (new HttpResultsFilter
                {
                    StringResultFn = tokenRequest =>
                    {
                        // To redeem an authorization code and get an access token,
                        // send an HTTP POST request to a common or tenant-specific Azure AD Authorization endpoint.
                        tokenRequest.RequestUri.ToString().Should().Be(
                            "https://login.microsoftonline.com/common/oauth2/token");
                        tokenRequest.Method.Should().Be("POST");
                        tokenRequest.ContentType.Should().Be("application/x-www-form-urlencoded");
                        // TODO: Test form data. Seems impossible: http://stackoverflow.com/questions/31630526/can-i-test-form-data-using-httpresultsfilter-callback
                        //formData["client_id"].Should().Be(Subject.ClientId);
                        //formData["client_secret"].Should().Be(Subject.ClientSecret);
                        //formData["redirect_uri"].Should().Be(Subject.CallbackUrl);
                        //formData["resource"].Should().Be(Subject.ResourceId);
                        return 
                        @"{
                          ""access_token"": ""eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1THdqcHdBSk9NOW4tQSJ9.eyJhdWQiOiJodHRwczovL3NlcnZpY2UuY29udG9zby5jb20vIiwiaXNzIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvN2ZlODE0NDctZGE1Ny00Mzg1LWJlY2ItNmRlNTdmMjE0NzdlLyIsImlhdCI6MTM4ODQ0MDg2MywibmJmIjoxMzg4NDQwODYzLCJleHAiOjEzODg0NDQ3NjMsInZlciI6IjEuMCIsInRpZCI6IjdmZTgxNDQ3LWRhNTctNDM4NS1iZWNiLTZkZTU3ZjIxNDc3ZSIsIm9pZCI6IjY4Mzg5YWUyLTYyZmEtNGIxOC05MWZlLTUzZGQxMDlkNzRmNSIsInVwbiI6ImZyYW5rbUBjb250b3NvLmNvbSIsInVuaXF1ZV9uYW1lIjoiZnJhbmttQGNvbnRvc28uY29tIiwic3ViIjoiZGVOcUlqOUlPRTlQV0pXYkhzZnRYdDJFYWJQVmwwQ2o4UUFtZWZSTFY5OCIsImZhbWlseV9uYW1lIjoiTWlsbGVyIiwiZ2l2ZW5fbmFtZSI6IkZyYW5rIiwiYXBwaWQiOiIyZDRkMTFhMi1mODE0LTQ2YTctODkwYS0yNzRhNzJhNzMwOWUiLCJhcHBpZGFjciI6IjAiLCJzY3AiOiJ1c2VyX2ltcGVyc29uYXRpb24iLCJhY3IiOiIxIn0.JZw8jC0gptZxVC-7l5sFkdnJgP3_tRjeQEPgUn28XctVe3QqmheLZw7QVZDPCyGycDWBaqy7FLpSekET_BftDkewRhyHk9FW_KeEz0ch2c3i08NGNDbr6XYGVayNuSesYk5Aw_p3ICRlUV1bqEwk-Jkzs9EEkQg4hbefqJS6yS1HoV_2EsEhpd_wCQpxK89WPs3hLYZETRJtG5kvCCEOvSHXmDE6eTHGTnEgsIk--UlPe275Dvou4gEAwLofhLDQbMSjnlV5VLsjimNBVcSRFShoxmQwBJR_b2011Y5IuD6St5zPnzruBbZYkGNurQK63TJPWmRd3mbJsGM0mf3CUQ"",
                          ""token_type"": ""Bearer"",
                          ""expires_in"": ""3600"",
                          ""expires_on"": ""1388444763"",
                          ""resource"": ""https://service.contoso.com/"",
                          ""refresh_token"": ""AwABAAAAvPM1KaPlrEqdFSBzjqfTGAMxZGUTdM0t4B4rTfgV29ghDOHRc2B-C_hHeJaJICqjZ3mY2b_YNqmf9SoAylD1PycGCB90xzZeEDg6oBzOIPfYsbDWNf621pKo2Q3GGTHYlmNfwoc-OlrxK69hkha2CF12azM_NYhgO668yfcUl4VBbiSHZyd1NVZG5QTIOcbObu3qnLutbpadZGAxqjIbMkQ2bQS09fTrjMBtDE3D6kSMIodpCecoANon9b0LATkpitimVCrl-NyfN3oyG4ZCWu18M9-vEou4Sq-1oMDzExgAf61noxzkNiaTecM-Ve5cq6wHqYQjfV9DOz4lbceuYCAA"",
                          ""scope"": ""user_impersonation"",
                          ""id_token"": ""eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJhdWQiOiIyZDRkMTFhMi1mODE0LTQ2YTctODkwYS0yNzRhNzJhNzMwOWUiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC83ZmU4MTQ0Ny1kYTU3LTQzODUtYmVjYi02ZGU1N2YyMTQ3N2UvIiwiaWF0IjoxMzg4NDQwODYzLCJuYmYiOjEzODg0NDA4NjMsImV4cCI6MTM4ODQ0NDc2MywidmVyIjoiMS4wIiwidGlkIjoiN2ZlODE0NDctZGE1Ny00Mzg1LWJlY2ItNmRlNTdmMjE0NzdlIiwib2lkIjoiNjgzODlhZTItNjJmYS00YjE4LTkxZmUtNTNkZDEwOWQ3NGY1IiwidXBuIjoiZnJhbmttQGNvbnRvc28uY29tIiwidW5pcXVlX25hbWUiOiJmcmFua21AY29udG9zby5jb20iLCJzdWIiOiJKV3ZZZENXUGhobHBTMVpzZjd5WVV4U2hVd3RVbTV5elBtd18talgzZkhZIiwiZmFtaWx5X25hbWUiOiJNaWxsZXIiLCJnaXZlbl9uYW1lIjoiRnJhbmsifQ.""
                        }";
                    }
                })
                {
                    var session = new AuthUserSession {State = "D79E5777-702E-4260-9A62-37F75FF22CCE"};

                    var response = Subject.Authenticate(mockAuthService.Object, session, new Authenticate());

                    session.IsAuthenticated.Should().BeTrue();
                    var tokens = session.GetOAuthTokens("aad");
                    tokens.Provider.Should().Be("aad");
                    tokens.AccessTokenSecret.Should().Be("eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1THdqcHdBSk9NOW4tQSJ9.eyJhdWQiOiJodHRwczovL3NlcnZpY2UuY29udG9zby5jb20vIiwiaXNzIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvN2ZlODE0NDctZGE1Ny00Mzg1LWJlY2ItNmRlNTdmMjE0NzdlLyIsImlhdCI6MTM4ODQ0MDg2MywibmJmIjoxMzg4NDQwODYzLCJleHAiOjEzODg0NDQ3NjMsInZlciI6IjEuMCIsInRpZCI6IjdmZTgxNDQ3LWRhNTctNDM4NS1iZWNiLTZkZTU3ZjIxNDc3ZSIsIm9pZCI6IjY4Mzg5YWUyLTYyZmEtNGIxOC05MWZlLTUzZGQxMDlkNzRmNSIsInVwbiI6ImZyYW5rbUBjb250b3NvLmNvbSIsInVuaXF1ZV9uYW1lIjoiZnJhbmttQGNvbnRvc28uY29tIiwic3ViIjoiZGVOcUlqOUlPRTlQV0pXYkhzZnRYdDJFYWJQVmwwQ2o4UUFtZWZSTFY5OCIsImZhbWlseV9uYW1lIjoiTWlsbGVyIiwiZ2l2ZW5fbmFtZSI6IkZyYW5rIiwiYXBwaWQiOiIyZDRkMTFhMi1mODE0LTQ2YTctODkwYS0yNzRhNzJhNzMwOWUiLCJhcHBpZGFjciI6IjAiLCJzY3AiOiJ1c2VyX2ltcGVyc29uYXRpb24iLCJhY3IiOiIxIn0.JZw8jC0gptZxVC-7l5sFkdnJgP3_tRjeQEPgUn28XctVe3QqmheLZw7QVZDPCyGycDWBaqy7FLpSekET_BftDkewRhyHk9FW_KeEz0ch2c3i08NGNDbr6XYGVayNuSesYk5Aw_p3ICRlUV1bqEwk-Jkzs9EEkQg4hbefqJS6yS1HoV_2EsEhpd_wCQpxK89WPs3hLYZETRJtG5kvCCEOvSHXmDE6eTHGTnEgsIk--UlPe275Dvou4gEAwLofhLDQbMSjnlV5VLsjimNBVcSRFShoxmQwBJR_b2011Y5IuD6St5zPnzruBbZYkGNurQK63TJPWmRd3mbJsGM0mf3CUQ");
                    tokens.RefreshTokenExpiry.Should().Be(DateTime.Parse("Mon, 30 Dec 2013 23:06:03 GMT").ToUniversalTime());
                    tokens.RefreshToken.Should().Be("AwABAAAAvPM1KaPlrEqdFSBzjqfTGAMxZGUTdM0t4B4rTfgV29ghDOHRc2B-C_hHeJaJICqjZ3mY2b_YNqmf9SoAylD1PycGCB90xzZeEDg6oBzOIPfYsbDWNf621pKo2Q3GGTHYlmNfwoc-OlrxK69hkha2CF12azM_NYhgO668yfcUl4VBbiSHZyd1NVZG5QTIOcbObu3qnLutbpadZGAxqjIbMkQ2bQS09fTrjMBtDE3D6kSMIodpCecoANon9b0LATkpitimVCrl-NyfN3oyG4ZCWu18M9-vEou4Sq-1oMDzExgAf61noxzkNiaTecM-Ve5cq6wHqYQjfV9DOz4lbceuYCAA");
                    tokens.UserId.Should().Be("68389ae2-62fa-4b18-91fe-53dd109d74f5"); // oid
                    tokens.UserName.Should().Be("*****@*****.**");
                    tokens.LastName.Should().Be("Miller");
                    tokens.FirstName.Should().Be("Frank");
                    tokens.DisplayName.Should().Be("Frank Miller");
                    session.UserName.Should().Be(tokens.UserName);
                    session.LastName.Should().Be(tokens.LastName);
                    session.FirstName.Should().Be(tokens.FirstName);
                    session.DisplayName.Should().Be(tokens.DisplayName);
                    var result = (IHttpResult) response;
                    result.Headers["Location"].Should().StartWith(
                        "http://localhost#s=1");
                }
            }
        }
Пример #20
0
 protected virtual void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary <string, string> authInfo)
 {
 }
Пример #21
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("name"))
                tokens.DisplayName = authInfo.GetValueOrDefault("name");

            if (authInfo.ContainsKey("FullName"))
            {
                tokens.FullName = authInfo.GetValueOrDefault("FullName");
                if (tokens.DisplayName.IsNullOrEmpty())
                    tokens.DisplayName = tokens.FullName;
            }

            if (authInfo.ContainsKey("Email"))
                tokens.Email = authInfo.GetValueOrDefault("Email");

            if (authInfo.ContainsKey("BirthDate"))
                tokens.BirthDate = authInfo.GetValueOrDefault("BirthDate").FromJsv<DateTime?>();

            if (authInfo.ContainsKey("BirthDateRaw"))
                tokens.BirthDateRaw = authInfo.GetValueOrDefault("BirthDateRaw");

            if (authInfo.ContainsKey("Country"))
                tokens.Country = authInfo.GetValueOrDefault("Country");

            if (authInfo.ContainsKey("Culture"))
                tokens.Culture = authInfo.GetValueOrDefault("Culture");

            if (authInfo.ContainsKey("Gender"))
                tokens.Gender = authInfo.GetValueOrDefault("Gender");

            if (authInfo.ContainsKey("MailAddress"))
                tokens.MailAddress = authInfo.GetValueOrDefault("MailAddress");

            if (authInfo.ContainsKey("Nickname"))
                tokens.Nickname = authInfo.GetValueOrDefault("Nickname");

            if (authInfo.ContainsKey("PostalCode"))
                tokens.PostalCode = authInfo.GetValueOrDefault("PostalCode");

            if (authInfo.ContainsKey("TimeZone"))
                tokens.TimeZone = authInfo.GetValueOrDefault("TimeZone");

            LoadUserOAuthProvider(userSession, tokens);
        }
		public static AuthUserSession GetNewSession2()
		{
			var oAuthUserSession = new AuthUserSession();
			return oAuthUserSession;
		}
        protected object Register(IUserAuthRepository userAuthRepository, AuthUserSession oAuthUserSession, Register register = null)
		{
			if (register == null)
				register = RegisterDto;

			var registrationService = GetRegistrationService(userAuthRepository, oAuthUserSession, requestContext);
			var response = registrationService.Post(register);
			Assert.That(response as IHttpError, Is.Null);
			return response;
		}
Пример #24
0
        protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            try
            {
                string json = "https://login.yandex.ru/info?format=json&oauth_token={0}".Fmt(tokens.AccessTokenSecret).GetJsonFromUrl();
                JsonObject obj = JsonObject.Parse(json);

                tokens.UserId = obj.Get("id");
                tokens.UserName = obj.Get("display_name");
                tokens.DisplayName = obj.Get("real_name");
                tokens.FirstName = obj.Get("first_name");
                tokens.LastName = obj.Get("last_name");
                tokens.Email = obj.Get("default_email");
                tokens.BirthDateRaw = obj.Get("birthday");

                LoadUserOAuthProvider(userSession, tokens);
            }
            catch (Exception ex)
            {
                Log.Error("Could not retrieve Yandex user info for '{0}'".Fmt(tokens.DisplayName), ex);
            }
        }
Пример #25
0
        protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            try
            {
                string json = "https://api.vk.com/method/users.get?user_ids={0}&fields=screen_name,bdate,city,country,timezone&oauth_token={0}"
                  .Fmt(tokens.UserId, tokens.AccessTokenSecret).GetJsonFromUrl();

                var obj = json.ArrayObjects()[0].GetUnescaped("response").ArrayObjects()[0];

                tokens.UserName = obj.Get("screen_name");
                tokens.DisplayName = obj.Get("screen_name");
                tokens.FirstName = obj.Get("first_name");
                tokens.LastName = obj.Get("last_name");
                tokens.BirthDateRaw = obj.Get("bdate");
                tokens.TimeZone = obj.Get("timezone");

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

            LoadUserOAuthProvider(userSession, tokens);
        }
Пример #26
0
        protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            try
            {
                var json = "https://api.github.com/user?access_token={0}".Fmt(tokens.AccessTokenSecret)
                  .GetStringFromUrl("*/*", UserRequestFilter);
                var obj = JsonObject.Parse(json);
                tokens.UserId = obj.Get("id");
                tokens.UserName = obj.Get("login");
                tokens.DisplayName = obj.Get("name");
                tokens.Email = obj.Get("email");
                tokens.Company = obj.Get("company");
                tokens.Country = obj.Get("country");

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

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

            LoadUserOAuthProvider(userSession, tokens);
        }
Пример #27
0
        protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            try
            {
                tokens.UserId = authInfo["user_id"];
                tokens.UserName = authInfo["username"];
                tokens.DisplayName = authInfo["name"];
                tokens.FirstName = authInfo["first_name"];
                tokens.LastName = authInfo["last_name"];
                tokens.Email = authInfo["email"];
                userSession.UserAuthName = tokens.Email;

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

                this.LoadUserOAuthProvider(userSession, tokens);
            }
            catch (Exception ex)
            {
                Log.Error("Could not retrieve Profile info for '{0}'".Fmt(tokens.DisplayName), ex);
            }
        }
Пример #28
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);
            }
        }
		public static RegisterService GetRegistrationService(
			IUserAuthRepository userAuthRepository,
			AuthUserSession oAuthUserSession = null,
			MockRequestContext requestContext = null)
		{
			if (requestContext == null)
				requestContext = new MockRequestContext();
			if (oAuthUserSession == null)
				oAuthUserSession = requestContext.ReloadSession();

			var httpReq = requestContext.Get<IHttpRequest>();
			var httpRes = requestContext.Get<IHttpResponse>();
			oAuthUserSession.Id = httpRes.CreateSessionId(httpReq);
			httpReq.Items[ServiceExtensions.RequestItemsSessionKey] = oAuthUserSession;

			var mockAppHost = new BasicAppHost {
				Container = requestContext.Container
			};

			requestContext.Container.Register(userAuthRepository);

		    var authService = new AuthenticateService {
                RequestContext = requestContext,
            };
            authService.SetResolver(mockAppHost);
            mockAppHost.Register(authService);

			var registrationService = new RegisterService {
				UserAuthRepo = userAuthRepository,
				RequestContext = requestContext,
				RegistrationValidator =
					new RegistrationValidator { UserAuthRepo = RegistrationServiceTests.GetStubRepo() },
			};
			registrationService.SetResolver(mockAppHost);

			return registrationService;
		}
Пример #30
0
 protected virtual Task LoadUserAuthInfoAsync(AuthUserSession userSession, IAuthTokens tokens, Dictionary <string, string> authInfo, CancellationToken token = default)
 {
     return(TypeConstants.EmptyTask);
 }
		protected object Login(string userName, string password, AuthUserSession oAuthUserSession = null)
		{
			if (oAuthUserSession == null)
				oAuthUserSession = requestContext.ReloadSession();

			var credentialsAuth = GetCredentialsAuthConfig();
			return credentialsAuth.Authenticate(service, oAuthUserSession,
				new Authenticate {
					provider = CredentialsAuthProvider.Name,
					UserName = RegisterDto.UserName,
					Password = RegisterDto.Password,
				});
		}
Пример #32
0
        public void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            if (userSession == null)
                return;

            try
            {
                using (PrincipalContext pc = new PrincipalContext(ContextType.Domain))
                {
                    var user = UserPrincipal.FindByIdentity(pc, userSession.UserAuthName);

                    tokens.DisplayName = user.DisplayName;
                    tokens.Email = user.EmailAddress;
                    tokens.FirstName = user.GivenName;
                    tokens.LastName = user.Surname;
                    tokens.FullName = (String.IsNullOrWhiteSpace(user.MiddleName))
                        ? "{0} {1}".Fmt(user.GivenName, user.Surname)
                        : "{0} {1} {2}".Fmt(user.GivenName, user.MiddleName, user.Surname);
                    tokens.PhoneNumber = user.VoiceTelephoneNumber;
                }
            }
            catch (MultipleMatchesException mmex)
            {
                Log.Error("Multiple windows user info for '{0}'".Fmt(userSession.UserAuthName), mmex);
            }
            catch (Exception ex)
            {
                Log.Error("Could not retrieve windows user info for '{0}'".Fmt(tokens.DisplayName), ex);
            }
        }
		protected void LoginWithFacebook(AuthUserSession oAuthUserSession)
		{
			MockAuthHttpGateway.Tokens = facebookGatewayTokens;
			var facebookAuth = GetFacebookAuthProvider();
			facebookAuth.OnAuthenticated(service, oAuthUserSession, facebookAuthTokens, new Dictionary<string, string>());
			Console.WriteLine("UserId: " + oAuthUserSession.UserAuthId);
		}
        protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            tokens.Gender = authInfo["gender"];
            if (tokens.Gender != "none")
                userSession.Gender = tokens.Gender;

            if (authInfo.ContainsKey("phone"))
                tokens.PhoneNumber = authInfo["phone"];
            userSession.PhoneNumber = tokens.PhoneNumber ?? userSession.PhoneNumber;

            if (authInfo.ContainsKey("birthday"))
            {
                tokens.BirthDateRaw = authInfo["birthday"];                

                long unixDateTime;
                if (long.TryParse(tokens.BirthDateRaw, out unixDateTime))
                {
                    tokens.BirthDate = unixDateTime.FromUnixTime();
                }
            }
            userSession.BirthDateRaw = tokens.BirthDateRaw ?? userSession.BirthDateRaw;
            userSession.BirthDate = tokens.BirthDate ?? userSession.BirthDate;

            if (authInfo.ContainsKey("facebook"))
                userSession.FacebookUserId = authInfo["facebook"];

            if (authInfo.ContainsKey("twitter"))
                userSession.TwitterUserId = authInfo["twitter"];

            base.LoadUserAuthInfo(userSession, tokens, authInfo);
        }
        private void VerifyNotAuthenticatedByToken()
        {
            Subject.CallbackUrl = "http://localhost/myapp/";
            using (TestAppHost())
            {
                var request = new MockHttpRequest("myapp", "GET", "text", "/myapp", new NameValueCollection
                {
                    {"code", "code123"},
                    {"state", "D79E5777-702E-4260-9A62-37F75FF22CCE"}
                }, Stream.Null, null);
                var mockAuthService = MockAuthService(request);
                using (new HttpResultsFilter
                {
                    StringResult =
                        @"{
                          ""access_token"": ""token456"",
                          ""id_token"": ""eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJhdWQiOiIyZDRkMTFhMi1mODE0LTQ2YTctODkwYS0yNzRhNzJhNzMwOWUiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC83ZmU4MTQ0Ny1kYTU3LTQzODUtYmVjYi02ZGU1N2YyMTQ3N2UvIiwiaWF0IjoxMzg4NDQwODYzLCJuYmYiOjEzODg0NDA4NjMsImV4cCI6MTM4ODQ0NDc2MywidmVyIjoiMS4wIiwidGlkIjoiN2ZlODE0NDctZGE1Ny00Mzg1LWJlY2ItNmRlNTdmMjE0NzdlIiwib2lkIjoiNjgzODlhZTItNjJmYS00YjE4LTkxZmUtNTNkZDEwOWQ3NGY1IiwidXBuIjoiZnJhbmttQGNvbnRvc28uY29tIiwidW5pcXVlX25hbWUiOiJmcmFua21AY29udG9zby5jb20iLCJzdWIiOiJKV3ZZZENXUGhobHBTMVpzZjd5WVV4U2hVd3RVbTV5elBtd18talgzZkhZIiwiZmFtaWx5X25hbWUiOiJNaWxsZXIiLCJnaXZlbl9uYW1lIjoiRnJhbmsifQ.""
                        }"
                })
                {
                    var session = new AuthUserSession();

                    try{ Subject.Authenticate(mockAuthService.Object, session, new Authenticate()); }
                    catch (UnauthorizedAccessException){}

                    session.IsAuthenticated.Should().BeFalse();
                }
            }
        }
        public void ShouldSaveExtendedInfoFromPayload()
        {
            using (TestAppHost())
            {
                Subject.SaveExtendedUserInfo = true;
                Subject.ClientId = "2d4d11a2-f814-46a7-890a-274a72a7309e";
                var request = new MockHttpRequest("myapp", "GET", "text", "/myapp", new NameValueCollection {
                    {"code", "c1"},
                    {"state", "s1" }
                }, Stream.Null, null);
                var mockAuthService = MockAuthService(request);
                using (new HttpResultsFilter
                {
                    StringResult = @"{
                          ""access_token"": ""t1"",
                          ""token_type"": ""Bearer"",
                          ""id_token"": ""eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJhdWQiOiIyZDRkMTFhMi1mODE0LTQ2YTctODkwYS0yNzRhNzJhNzMwOWUiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC83ZmU4MTQ0Ny1kYTU3LTQzODUtYmVjYi02ZGU1N2YyMTQ3N2UvIiwiaWF0IjoxMzg4NDQwODYzLCJuYmYiOjEzODg0NDA4NjMsImV4cCI6MTM4ODQ0NDc2MywidmVyIjoiMS4wIiwidGlkIjoiN2ZlODE0NDctZGE1Ny00Mzg1LWJlY2ItNmRlNTdmMjE0NzdlIiwib2lkIjoiNjgzODlhZTItNjJmYS00YjE4LTkxZmUtNTNkZDEwOWQ3NGY1IiwidXBuIjoiZnJhbmttQGNvbnRvc28uY29tIiwidW5pcXVlX25hbWUiOiJmcmFua21AY29udG9zby5jb20iLCJzdWIiOiJKV3ZZZENXUGhobHBTMVpzZjd5WVV4U2hVd3RVbTV5elBtd18talgzZkhZIiwiZmFtaWx5X25hbWUiOiJNaWxsZXIiLCJnaXZlbl9uYW1lIjoiRnJhbmsifQ.""
                        }"
                })
                {
                    var session = new AuthUserSession { State = "s1" };

                    Subject.Authenticate(mockAuthService.Object, session, new Authenticate());

                    var tokens = session.GetOAuthTokens("aad");
                    var items = tokens.Items;
                    items["token_type"].Should().Be("Bearer");
                    items["iss"].Should().Be("https://sts.windows.net/7fe81447-da57-4385-becb-6de57f21477e/");
                    items["sub"].Should().Be("JWvYdCWPhhlpS1Zsf7yYUxShUwtUm5yzPmw_-jX3fHY");
                }
            }
        }
        public void ShouldSetReferrerFromRedirectParam()
        {
            using (TestAppHost())
            {
                var request = new MockHttpRequest("myapp", "GET", "text", "/myapp", new NameValueCollection {
                    {"redirect", "http://localhost/myapp/secure-resource"}
                }, Stream.Null, null);
                var mockAuthService = MockAuthService(request);
                var session = new AuthUserSession();
                
                Subject.Authenticate(mockAuthService.Object, session, new Authenticate());

                session.ReferrerUrl.Should().Be("http://localhost/myapp/secure-resource");
            }
        }
        public void ShouldAbortIfStateValuesDoNotMatch()
        {
            // If the state value in the response matches the state value in the request, 
            // the application should store the authorization code for use in the access token request.
            using (TestAppHost())
            {
                Subject.ClientId = "2d4d11a2-f814-46a7-890a-274a72a7309e";
                Subject.CallbackUrl = "http://localhost/myapp/";
                var request = new MockHttpRequest("myapp", "GET", "text", "/myapp", new NameValueCollection {
                    {"code", "code123"},
                    {"session_state", "dontcare"},
                    {"state", "state123" }
                }, Stream.Null, null);
                var mockAuthService = MockAuthService(request);
                using (new HttpResultsFilter
                {
                    StringResultFn = tokenRequest =>
                    {
                        Assert.Fail("Should never have made token request since the state was not matched");
                        return @"{
                          ""access_token"": ""fake token"",
                          ""id_token"": ""eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJhdWQiOiIyZDRkMTFhMi1mODE0LTQ2YTctODkwYS0yNzRhNzJhNzMwOWUiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC83ZmU4MTQ0Ny1kYTU3LTQzODUtYmVjYi02ZGU1N2YyMTQ3N2UvIiwiaWF0IjoxMzg4NDQwODYzLCJuYmYiOjEzODg0NDA4NjMsImV4cCI6MTM4ODQ0NDc2MywidmVyIjoiMS4wIiwidGlkIjoiN2ZlODE0NDctZGE1Ny00Mzg1LWJlY2ItNmRlNTdmMjE0NzdlIiwib2lkIjoiNjgzODlhZTItNjJmYS00YjE4LTkxZmUtNTNkZDEwOWQ3NGY1IiwidXBuIjoiZnJhbmttQGNvbnRvc28uY29tIiwidW5pcXVlX25hbWUiOiJmcmFua21AY29udG9zby5jb20iLCJzdWIiOiJKV3ZZZENXUGhobHBTMVpzZjd5WVV4U2hVd3RVbTV5elBtd18talgzZkhZIiwiZmFtaWx5X25hbWUiOiJNaWxsZXIiLCJnaXZlbl9uYW1lIjoiRnJhbmsifQ.""
                        }";

                    }
                })
                {
                    var session = new AuthUserSession
                    {
                        State = "state133" // Not the same as the state in the request above
                    };

                    try { Subject.Authenticate(mockAuthService.Object, session, new Authenticate()); }
                    catch (UnauthorizedAccessException){}

                    session.IsAuthenticated.Should().BeFalse("Should not be authenticated");
                }
            }
        }
Пример #39
0
        protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            try
            {
                var json = "https://api.github.com/user?access_token={0}"
                  .Fmt(tokens.AccessTokenSecret).GetStringFromUrl("*/*", UserRequestFilter);
                var obj = JsonObject.Parse(json);

                tokens.UserId = obj.Get("id");
                tokens.UserName = obj.Get("login");
                tokens.DisplayName = obj.Get("name");
                tokens.Email = obj.Get("email");
                tokens.Company = obj.Get("company");
                tokens.Country = obj.Get("country");

                LoadUserOAuthProvider(userSession, tokens);
            }
            catch (Exception ex)
            {
                Log.Error("Could not retrieve github user info for '{0}'".Fmt(tokens.DisplayName), ex);
            }
        }
    protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary<string, string> authInfo)
    {
      try
      {

        //sig = md5( request_params_composed_string + md5(access_token + application_secret_key)  )

        string innerSignature = Encoding.UTF8.GetBytes(tokens.AccessTokenSecret + ConsumerSecret).ToMd5Hash();
        string signature = Encoding.UTF8.GetBytes("application_key={0}".Fmt(PublicKey) + innerSignature).ToMd5Hash();

        string payload = "access_token={0}&sig={1}&application_key={2}".Fmt(tokens.AccessTokenSecret, signature, PublicKey);

        string json = "http://api.odnoklassniki.ru/api/users/getCurrentUser".PostToUrl(payload, "*/*", RequestFilter);

        JsonObject obj = JsonObject.Parse(json);

        if (!obj.Get("error").IsNullOrEmpty())
        {
          Log.Error("Could not retrieve Odnoklassniki user info for '{0}', Response:{1}".Fmt(tokens.DisplayName, json));
          return;
        }

        //response fields info: http://apiok.ru/wiki/display/api/users.getCurrentUser+ru
        var location = JsonObject.Parse(obj.GetUnescaped("location"));

        tokens.UserId = obj.Get("uid");
        tokens.DisplayName = obj.Get("name");
        tokens.FirstName = obj.Get("first_name");
        tokens.LastName = obj.Get("last_name");
        tokens.BirthDateRaw = obj.Get("birthday");
        tokens.Language = obj.Get("locale");
        tokens.Country = location.Get("countryCode");
        tokens.City = location.Get("city");
        tokens.Gender = obj.Get("gender");

        LoadUserOAuthProvider(userSession, tokens);
      }
      catch (Exception ex)
      {
        Log.Error("Could not retrieve Odnoklassniki user info for '{0}'".Fmt(tokens.DisplayName), ex);
      }
    }
Пример #41
0
 protected virtual void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary<string, string> authInfo) { }
        public void ShouldSaveOAuth2StateValue()
        {
            using (TestAppHost())
            {
                var session = new AuthUserSession();

                var response = Subject.Authenticate(MockAuthService().Object, session, new Authenticate());

                var result = (IHttpResult)response;
                var codeRequest = new Uri(result.Headers["Location"]);
                var query = PclExportClient.Instance.ParseQueryString(codeRequest.Query);
                var state = query["state"];
                session.State.Should().Be(state);
            }            
        }
Пример #43
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);
        }
		public static RegisterService GetRegistrationService(
            IUserAuthRepository userAuthRepository,
			AuthUserSession oAuthUserSession = null,
            BasicRequest request = null)
		{
			if (request == null)
                request = new BasicRequest();
			if (oAuthUserSession == null)
				oAuthUserSession = request.ReloadSession();

            oAuthUserSession.Id = request.Response.CreateSessionId(request);
            request.Items[ServiceExtensions.RequestItemsSessionKey] = oAuthUserSession;

			var mockAppHost = new BasicAppHost();

            mockAppHost.Container.Register<IAuthRepository>(userAuthRepository);

		    var authService = new AuthenticateService {
                Request = request,
            };
            authService.SetResolver(mockAppHost);
            mockAppHost.Register(authService);

			var registrationService = new RegisterService {
				AuthRepo = userAuthRepository,
				Request = request,
				RegistrationValidator =
					new RegistrationValidator { UserAuthRepo = RegistrationServiceTests.GetStubRepo() },
			};
			registrationService.SetResolver(mockAppHost);

			return registrationService;
		}
        protected AuthUserSession RegisterAndLogin(IUserAuthRepository userAuthRepository, AuthUserSession oAuthUserSession)
		{
			Register(userAuthRepository, oAuthUserSession);

			Login(RegisterDto.UserName, RegisterDto.Password, oAuthUserSession);

			oAuthUserSession = requestContext.ReloadSession();
			return oAuthUserSession;
		}
Пример #46
0
        protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            try
            {
                tokens.UserId = authInfo["user_id"];
                tokens.UserName = authInfo["username"];
                tokens.DisplayName = authInfo["name"];
                tokens.FirstName = authInfo["first_name"];
                tokens.LastName = authInfo["last_name"];
                tokens.Email = authInfo["email"];
                userSession.UserAuthName = tokens.Email;

                this.LoadUserOAuthProvider(userSession, tokens);
            }
            catch (Exception ex)
            {
                Log.Error("Could not retrieve Profile info for '{0}'".Fmt(tokens.DisplayName), ex);
            }
        }