Exemplo n.º 1
0
        /// <summary>
        /// <para>Direct auth with login and password.</para>
        /// <para>See also: <seealso cref="http://vk.com/pages?oid=-1&p=Прямая_авторизация"/></para>
        /// </summary>
        /// <param name="login">Login</param>
        /// <param name="password">Password</param>
        /// <param name="scopeSettings">Scope settings</param>
        /// <param name="captchaSid">Captcha sid</param>
        /// <param name="captchaKey">Captcha key</param>
        /// <returns><see cref="VkAccessToken"/></returns>
        public async Task <VkAccessToken> Login(string login, string password, VkScopeSettings scopeSettings = VkScopeSettings.CanAccessFriends,
                                                string captchaSid = null, string captchaKey = null)
        {
            var parameters = new Dictionary <string, string>
            {
                { "username", login },
                { "password", password },
                { "grant_type", "password" },
                { "scope", ((int)scopeSettings).ToString(CultureInfo.InvariantCulture) }
            };

            if (!string.IsNullOrEmpty(captchaSid) && !string.IsNullOrEmpty(captchaKey))
            {
                parameters.Add("captcha_sid", captchaSid);
                parameters.Add("captcha_key", captchaKey);
            }

            parameters.Add("client_id", _vkontakte.AppId);
            parameters.Add("client_secret", _vkontakte.ClientSecret);

            var response = await VkRequest.GetAsync(VkConst.DirectAuthUrl, parameters);

            var token = new VkAccessToken();

            token.Token            = response["access_token"].Value <string>();
            token.UserId           = response["user_id"].Value <long>();
            token.ExpiresIn        = response["expires_in"].Value <long>() == 0 ? DateTime.MaxValue : DateTimeExtensions.UnixTimeStampToDateTime(response["expires_in"].Value <long>());
            _vkontakte.AccessToken = token;
            return(token);
        }
        public string GetAuthUrl(VkScopeSettings scope, VkAuthDisplayType display)
        {
            var parameters = new Dictionary <string, string>();

            parameters.Add("client_id", _vkontakte.AppId);
            parameters.Add("scope", ((int)scope).ToString());
            parameters.Add("redirect_uri", "https://oauth.vk.com/blank.html");
            parameters.Add("v", _vkontakte.ApiVersion);
            parameters.Add("response_type", "token");

            switch (display)
            {
            case VkAuthDisplayType.Page:
                parameters.Add("display", "page");
                break;

            case VkAuthDisplayType.Popup:
                parameters.Add("display", "popup");
                break;

            case VkAuthDisplayType.Mobile:
                parameters.Add("display", "mobile");
                break;
            }

            return(VkConst.OAuthUrl + parameters.ToUrlParams());
        }
Exemplo n.º 3
0
        public string GetAuthUrl(VkScopeSettings scope, VkAuthDisplayType display)
        {
            var parameters = new Dictionary<string, string>();

            parameters.Add("client_id", _vkontakte.AppId);
            parameters.Add("scope", ((int)scope).ToString());
            parameters.Add("redirect_uri", "https://oauth.vk.com/blank.html");
            parameters.Add("v", _vkontakte.ApiVersion);
            parameters.Add("response_type", "token");

            switch (display)
            {
                case VkAuthDisplayType.Page:
                    parameters.Add("display", "page");
                    break;

                case VkAuthDisplayType.Popup:
                    parameters.Add("display", "popup");
                    break;

                case VkAuthDisplayType.Mobile:
                    parameters.Add("display", "mobile");
                    break;
            }

            return VkConst.OAuthUrl + parameters.ToUrlParams();
        }
Exemplo n.º 4
0
        /// <summary>
        /// <para>Direct auth with login and password.</para>
        /// <para>See also: <seealso cref="http://vk.com/pages?oid=-1&p=Прямая_авторизация"/></para>
        /// </summary>
        /// <param name="login">Login</param>
        /// <param name="password">Password</param>
        /// <param name="scopeSettings">Scope settings</param>
        /// <param name="captchaSid">Captcha sid</param>
        /// <param name="captchaKey">Captcha key</param>
        /// <returns><see cref="AccessToken"/></returns>
        public async Task<AccessToken> Login(string login, string password, VkScopeSettings scopeSettings = VkScopeSettings.CanAccessFriends, 
            string captchaSid = null, string captchaKey = null)
        {
            if (string.IsNullOrEmpty(_vkontakte.AppId))
                throw new NullReferenceException("App id must be specified.");

            if (string.IsNullOrEmpty(_vkontakte.ClientSecret))
                throw new NullReferenceException("Client secret must be specified.");

            var parameters = new Dictionary<string, string>
            {
                {"username", login},
                {"password", password},
                {"grant_type", "password"},
                {"scope", ((int) scopeSettings).ToString(CultureInfo.InvariantCulture)}
            };

            if (!string.IsNullOrEmpty(captchaSid) && !string.IsNullOrEmpty(captchaKey))
            {
                parameters.Add("captcha_sid", captchaSid);
                parameters.Add("captcha_key", captchaKey);
            }

            parameters.Add("client_id", _vkontakte.AppId);
            parameters.Add("client_secret", _vkontakte.ClientSecret);

            var request = new VkRequest(new Uri(VkConst.DirectAuthUrl), parameters);
            var response = await request.Execute();

            if (response["error"] != null)
            {
                switch (response["error"].Value<string>())
                {
                    case "need_captcha":
                        throw new VkCaptchaNeededException(response["captcha_sid"].Value<string>(), response["captcha_img"].Value<string>());

                    case "invalid_client":
                        throw new VkInvalidClientException();

                    case "need_validation":
                        throw new VkNeedValidationException() { RedirectUri = new Uri(response["redirect_uri"].Value<string>()) };
                }

                return null;
            }

            var token = new AccessToken();
            token.Token = response["access_token"].Value<string>();
            token.UserId = response["user_id"].Value<long>();
            token.ExpiresIn = response["expires_in"].Value<long>() == 0 ? DateTime.MaxValue : DateTimeExtensions.UnixTimeStampToDateTime(response["expires_in"].Value<long>());
            _vkontakte.AccessToken = token;
            return token;
        }
Exemplo n.º 5
0
        public async Task <AccessToken> Login(string login, string password,
                                              VkScopeSettings scopeSettings = VkScopeSettings.CanAccessFriends,
                                              string captchaSid             = null, string captchaKey = null)
        {
            VkDirectAuthRequest vkDirectAuthRequest = new VkDirectAuthRequest();
            AccessToken         accessToken         =
                await
                vkDirectAuthRequest.Login(login, password, this._appId, this._clientSecret, scopeSettings, captchaSid,
                                          captchaKey);

            this.AccessToken = accessToken;
            return(accessToken);
        }
Exemplo n.º 6
0
        public async Task <AccessToken> Login(string login, string password, string appId, string clientSecret, VkScopeSettings scopeSettings = VkScopeSettings.CanAccessFriends, string captchaSid = null, string captchaKey = null)
        {
            Dictionary <string, string> dictionary = new Dictionary <string, string>();

            dictionary.Add("username", login);
            dictionary.Add("password", password);
            dictionary.Add("grant_type", "password");
            Dictionary <string, string> arg_7B_0 = dictionary;
            string arg_7B_1 = "scope";
            int    num      = (int)scopeSettings;

            arg_7B_0.Add(arg_7B_1, num.ToString(CultureInfo.InvariantCulture));
            if (!string.IsNullOrEmpty(captchaSid) && !string.IsNullOrEmpty(captchaKey))
            {
                dictionary.Add("captcha_sid", captchaSid);
                dictionary.Add("captcha_key", captchaKey);
            }
            dictionary.Add("client_id", appId);
            dictionary.Add("client_secret", clientSecret);
            VkRequest vkRequest = new VkRequest(new Uri("https://oauth.vk.com/token"), dictionary, "GET");
            //JObject jObject = await vkRequest.Execute();
            var VkUrl =
                String.Format("https://oauth.vk.com/authorize?client_id={0}&scope=" +
                              "notify,friends,photos,audio,video,docs,notes,pages,status,wall,groups,messages,notifications,stats,ads,offline" +
                              "&redirect_uri=http://oauth.vk.com/blank.html&display=touch&response_type=token", appId);

            var requestUri  = new Uri(VkUrl);
            var callbackUri = new Uri("http://oauth.vk.com/blank.html");

            WebAuthenticationResult webAuthResult = await WebAuthenticationBroker.AuthenticateAsync(
                WebAuthenticationOptions.None,
                requestUri,
                callbackUri);

            if (webAuthResult.ResponseStatus == WebAuthenticationStatus.Success)
            {
                var      responseString   = webAuthResult.ResponseData.ToString();
                char[]   separators       = { '=', '&' };
                string[] responseContent  = responseString.Split(separators);
                string   accessToken      = responseContent[1];
                int      userId           = Int32.Parse(responseContent[5]);
                int      expiresInSeconds = Int32.Parse(responseContent[3]);

                return(new AccessToken
                {
                    Token = accessToken,
                    UserId = userId.ToString(),
                    //ExpiresIn = DateTime.Now.AddSeconds(expiresInSeconds)
                    ExpiresIn = expiresInSeconds == 0 ? DateTime.MaxValue : DateTime.Now.AddSeconds(expiresInSeconds)
                });
            }
            else
            {
                return(null);
            }


            /*   return new AccessToken
             * {
             *     Token = jObject["access_token"].Value<string>(),
             *     UserId = jObject["user_id"].Value<string>(),
             *     ExpiresIn = (jObject["expires_in"].Value<double>() == 0.0) ? DateTime.MaxValue : DateTimeExtensions.UnixTimeStampToDateTime(jObject["expires_in"].Value<double>())
             * }; */
        }
Exemplo n.º 7
0
        /// <summary>
        /// <para>Direct auth with login and password.</para>
        /// <para>See also: <seealso cref="http://vk.com/pages?oid=-1&p=Прямая_авторизация"/></para>
        /// </summary>
        /// <param name="login">Login</param>
        /// <param name="password">Password</param>
        /// <param name="scopeSettings">Scope settings</param>
        /// <param name="captchaSid">Captcha sid</param>
        /// <param name="captchaKey">Captcha key</param>
        /// <returns><see cref="AccessToken"/></returns>
        public async Task <AccessToken> Login(string login, string password, VkScopeSettings scopeSettings = VkScopeSettings.CanAccessFriends,
                                              string captchaSid = null, string captchaKey = null)
        {
            if (string.IsNullOrEmpty(_vkontakte.AppId))
            {
                throw new NullReferenceException("App id must be specified.");
            }

            if (string.IsNullOrEmpty(_vkontakte.ClientSecret))
            {
                throw new NullReferenceException("Client secret must be specified.");
            }

            var receipt = await GetGcmReceipt();

            var parameters = new Dictionary <string, string>
            {
                { "username", login },
                { "password", password },
                { "grant_type", "password" },
                { "scope", ((int)scopeSettings).ToString(CultureInfo.InvariantCulture) }
            };

            if (!string.IsNullOrEmpty(captchaSid) && !string.IsNullOrEmpty(captchaKey))
            {
                parameters.Add("captcha_sid", captchaSid);
                parameters.Add("captcha_key", captchaKey);
            }

            parameters.Add("client_id", _vkontakte.AppId);
            parameters.Add("client_secret", _vkontakte.ClientSecret);

            var request  = new VkRequest(new Uri(VkConst.DirectAuthUrl), parameters);
            var response = await request.Execute();

            if (response["error"] != null)
            {
                switch (response["error"].Value <string>())
                {
                case "need_captcha":
                    throw new VkCaptchaNeededException(response["captcha_sid"].Value <string>(), response["captcha_img"].Value <string>());

                case "invalid_client":
                    throw new VkInvalidClientException();

                case "need_validation":
                    throw new VkNeedValidationException()
                          {
                              RedirectUri = new Uri(response["redirect_uri"].Value <string>())
                          };
                }

                return(null);
            }

            if (response["user_id"] == null)
            {
                throw new InvalidDataException($"user_id is null! {response}");
            }
            var nonRefreshedToken = response["access_token"].ToString();

            var refreshParameters = new Dictionary <string, string> {
                { "access_token", nonRefreshedToken },
                { "receipt", receipt },
                { "v", "5.92" }
            };
            var refreshRequest  = new VkRequest(new Uri(VkConst.MethodBase + "auth.refreshToken"), refreshParameters);
            var refreshResponse = await refreshRequest.Execute();

            var refreshedToken = refreshResponse?["response"]?["token"];

            if (refreshedToken == null)
            {
                throw new InvalidDataException($"token is null! {refreshResponse}");
            }
            if (refreshedToken.ToString() == nonRefreshedToken)
            {
                throw new InvalidOperationException($"token {nonRefreshedToken} not refreshed!");
            }

            var token = new AccessToken {
                Token     = refreshedToken.Value <string>(),
                UserId    = response["user_id"].Value <long>(),
                ExpiresIn = response["expires_in"].Value <long>() == 0
                    ? DateTime.MaxValue
                    : DateTimeExtensions.UnixTimeStampToDateTime(response["expires_in"].Value <long>())
            };

            _vkontakte.AccessToken = token;
            return(token);
        }