protected virtual async Task <bool> OnSignInBySocial(string socialToken, OAuthType socialType, CancellationTokenSource cts)
        {
            if (socialToken.IsNullOrEmtpy())
            {
                throw new Exception("Неудалось получить доступ к социальной сети");
            }
            try
            {
                var token = await AuthService.SocialSignIn(socialToken, socialType.GetSocialType(), cts);

                AuthSettings.Token = token;

                return(await Mvx.Resolve <ISessionService>().StartByToken(token));
            }
            catch (ConnectionException ex)
            {
                OnConnectionException(ex);
            }
            catch (Exception ex)
            {
                OnException(ex, "Не удалось завершить авторизацию");
            }

            return(false);
        }
Example #2
0
        public async Task <string> SignInTo(OAuthType socialType)
        {
            switch (socialType)
            {
            case OAuthType.Facebook:
                return(await FacebookLogin());

            case OAuthType.VK:
                return(await VKLogin());
            }

            return(null);
        }
 public static Hammock.Authentication.OAuth.OAuthCredentials createOAuthCredentials(OAuthType type, String strToken, String strSecret, String strVerifier, String strCallBack )
 {
     Hammock.Authentication.OAuth.OAuthCredentials credentials = new Hammock.Authentication.OAuth.OAuthCredentials()
     {
         Type =type,
         SignatureMethod = Hammock.Authentication.OAuth.OAuthSignatureMethod.HmacSha1,
         ParameterHandling = Hammock.Authentication.OAuth.OAuthParameterHandling.HttpAuthorizationHeader,
         ConsumerKey = SampleApp.Sources.democlient.ApiCredentials.CLIENT.key,
         ConsumerSecret = SampleApp.Sources.democlient.ApiCredentials.CLIENT.secret,
         Token = strToken,
         TokenSecret = strSecret,
         Verifier = strVerifier,
         CallbackUrl = strCallBack
     };
     return credentials;
 }
Example #4
0
        public static OAuthCredentials createOAuthCredentials(OAuthType type, String strToken, String strSecret, String strVerifier, String strCallBack)
        {
            OAuthCredentials credentials = new OAuthCredentials()
            {
                Type              = type,
                SignatureMethod   = OAuthSignatureMethod.HmacSha1,
                ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
                ConsumerKey       = ApiCredentials.CLIENT.key,
                ConsumerSecret    = ApiCredentials.CLIENT.secret,
                Token             = strToken,
                TokenSecret       = strSecret,
                Verifier          = strVerifier,
                CallbackUrl       = strCallBack
            };

            return(credentials);
        }
Example #5
0
        public static bool IsOAuthReady(OAuthType oAuthType)
        {
            var configInfo = Utils.GetConfigInfo();

            if (oAuthType == OAuthType.Weibo)
            {
                return(configInfo.IsWeibo);
            }
            if (oAuthType == OAuthType.Weixin)
            {
                return(configInfo.IsWeixin);
            }
            if (oAuthType == OAuthType.Qq)
            {
                return(configInfo.IsQq);
            }
            return(false);
        }
Example #6
0
        public OAuthClient(string clientId, string secret, string baseAddress, OAuthType type)
        {
            this._clientId = clientId;
            this._secret = secret;
            Type = type;
            if (string.IsNullOrWhiteSpace(clientId) && string.IsNullOrWhiteSpace(secret))
            {
                throw new ArgumentNullException(NullExceptionStr);
            }
            else if (string.IsNullOrWhiteSpace(baseAddress))
            {
                throw new ArgumentNullException(NullExceptionStr);
            }

            _httpClient.BaseAddress = new Uri(baseAddress);
          
            GetAccessToken();
        }
Example #7
0
        public IHttpActionResult GetAuth(string type)
        {
            try
            {
                var request = Context.GetCurrentRequest();

                var config      = Utils.GetConfigInfo();
                var oAuthType   = OAuthType.Parse(type);
                var redirectUrl = request.GetQueryString("redirectUrl");
                if (string.IsNullOrEmpty(redirectUrl))
                {
                    redirectUrl = ApiUtils.GetHomeUrl();
                }

                var url = string.Empty;

                if (oAuthType == OAuthType.Weibo)
                {
                    var client = new WeiboClient(config.WeiboAppKey, config.WeiboAppSecret, redirectUrl);
                    url = client.GetAuthorizationUrl();
                }
                else if (oAuthType == OAuthType.Weixin)
                {
                    var client = new WeixinClient(config.WeixinAppId, config.WeixinAppSecret, redirectUrl);
                    url = client.GetAuthorizationUrl();
                }
                else if (oAuthType == OAuthType.Qq)
                {
                    var client = new QqClient(config.QqAppId, config.QqAppKey, redirectUrl);
                    url = client.GetAuthorizationUrl();
                }

                if (!string.IsNullOrEmpty(url))
                {
                    HttpContext.Current.Response.Redirect(url);
                }

                return(BadRequest("类型不正确"));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
Example #8
0
        public async Task <ActionResult> GetAuth([FromRoute] string type, [FromQuery] GetAuthRequest request)
        {
            var oAuthType   = OAuthType.Parse(type);
            var host        = ApiUtils.GetHost(Request);
            var redirectUrl = request.RedirectUrl;

            if (string.IsNullOrEmpty(redirectUrl))
            {
                redirectUrl = ApiUtils.GetHomeUrl();
            }

            var url = string.Empty;

            if (oAuthType == OAuthType.Weixin)
            {
                var settings = await _loginManager.GetWeixinSettingsAsync();

                var client = new WeixinClient(settings.WeixinAppId, settings.WeixinAppSecret, host, redirectUrl);
                url = client.GetAuthorizationUrl();
            }
            else if (oAuthType == OAuthType.Qq)
            {
                var settings = await _loginManager.GetQqSettingsAsync();

                var client = new QqClient(settings.QqAppId, settings.QqAppKey, host, redirectUrl);
                url = client.GetAuthorizationUrl();
            }
            else if (oAuthType == OAuthType.Weibo)
            {
                var settings = await _loginManager.GetWeiboSettingsAsync();

                var client = new WeiboClient(settings.WeiboAppKey, settings.WeiboAppSecret, host, redirectUrl);
                url = client.GetAuthorizationUrl();
            }

            if (!string.IsNullOrEmpty(url))
            {
                return(Redirect(url));
            }

            return(this.Error("类型不正确"));
        }
    public void Authenticate_ShouldEncodeOAuthTokenParameter(OAuthType type, string value, string expected)
    {
        // Arrange
        const string url = "https://no-query.string";

        var client  = new RestClient(url);
        var request = new RestRequest();

        _authenticator.Type  = type;
        _authenticator.Token = value;

        // Act
        _authenticator.Authenticate(client, request);

        // Assert
        var authParameter = request.Parameters.Single(x => x.Name == KnownHeaders.Authorization);
        var authHeader    = (string)authParameter.Value;

        Assert.NotNull(authHeader);
        Assert.Contains($"oauth_token=\"{expected}\"", authHeader);
    }
        public static SocialType GetSocialType(this OAuthType oauthType)
        {
            switch (oauthType)
            {
            case OAuthType.Facebook:
                return(SocialType.Facebook);

            case OAuthType.GPlus:
                return(SocialType.GPlus);

            case OAuthType.OK:
                return(SocialType.OK);

            case OAuthType.Twitter:
                return(SocialType.Twitter);

            case OAuthType.VK:
                return(SocialType.VK);
            }
            return(SocialType.Unknown);
        }
        public async Task SignInTo(OAuthType socialType, string cancelledError, string error, CancellationTokenSource cts)
        {
            try
            {
                var socialToken = await OAuthService.SignInTo(socialType);

                if (await OnSignInBySocial(socialToken, socialType, cts))
                {
                    await UserDialogs.Alert("Вы успешно выполнили вход");

                    ChangePresentation(new Base.Core.PresentationHints.NavigateToDefaultViewModelHint());
                }
            }
            catch (OperationCanceledException)
            {
                await UserDialogs.Alert(cancelledError);
            }
            catch (Exception ex)
            {
                OnException(ex, error);
            }
        }
Example #12
0
        public IHttpActionResult GetRedirect(string type)
        {
            try
            {
                var request = Context.GetCurrentRequest();

                var config    = Utils.GetConfigInfo();
                var oAuthType = OAuthType.Parse(type);

                var redirectUrl = request.GetQueryString("redirectUrl");
                var code        = request.GetQueryString("code");
                var userName    = string.Empty;

                if (oAuthType == OAuthType.Weibo)
                {
                    var client = new WeiboClient(config.WeiboAppKey, config.WeiboAppSecret, redirectUrl);

                    string name;
                    string screenName;
                    string avatarLarge;
                    string gender;
                    string uniqueId;
                    client.GetUserInfo(code, out name, out screenName, out avatarLarge, out gender, out uniqueId);

                    userName = OAuthDao.GetUserName(OAuthType.Weibo.Value, uniqueId);
                    if (string.IsNullOrEmpty(userName))
                    {
                        var userInfo = Context.UserApi.NewInstance();
                        userInfo.UserName = Context.UserApi.IsUserNameExists(name)
                            ? Regex.Replace(Convert.ToBase64String(Guid.NewGuid().ToByteArray()), "[/+=]", "")
                            : name;
                        userInfo.DisplayName = screenName;
                        userInfo.AvatarUrl   = avatarLarge;
                        userInfo.Gender      = gender;

                        string errorMessage;
                        Context.UserApi.Insert(userInfo, Guid.NewGuid().ToString(), out errorMessage);
                        userName = userInfo.UserName;

                        OAuthDao.Insert(new OAuthInfo
                        {
                            Source   = OAuthType.Weibo.Value,
                            UniqueId = uniqueId,
                            UserName = userName
                        });
                    }
                }
                else if (oAuthType == OAuthType.Weixin)
                {
                    var client = new WeixinClient(config.WeixinAppId, config.WeixinAppSecret, redirectUrl);

                    string nickname;
                    string headimgurl;
                    string gender;
                    string unionid;
                    client.GetUserInfo(code, out nickname, out headimgurl, out gender, out unionid);

                    userName = OAuthDao.GetUserName(OAuthType.Weixin.Value, unionid);
                    if (string.IsNullOrEmpty(userName))
                    {
                        var userInfo = Context.UserApi.NewInstance();
                        userInfo.UserName = Context.UserApi.IsUserNameExists(nickname)
                            ? Regex.Replace(Convert.ToBase64String(Guid.NewGuid().ToByteArray()), "[/+=]", "")
                            : nickname;
                        userInfo.DisplayName = nickname;
                        userInfo.AvatarUrl   = headimgurl;
                        userInfo.Gender      = gender;

                        string errorMessage;
                        Context.UserApi.Insert(userInfo, Guid.NewGuid().ToString(), out errorMessage);
                        userName = userInfo.UserName;

                        OAuthDao.Insert(new OAuthInfo
                        {
                            Source   = OAuthType.Weixin.Value,
                            UniqueId = unionid,
                            UserName = userName
                        });
                    }
                }
                else if (oAuthType == OAuthType.Qq)
                {
                    var client = new QqClient(config.QqAppId, config.QqAppKey, redirectUrl);

                    string displayName;
                    string avatarUrl;
                    string gender;
                    string uniqueId;
                    client.GetUserInfo(code, out displayName, out avatarUrl, out gender, out uniqueId);

                    userName = OAuthDao.GetUserName(OAuthType.Qq.Value, uniqueId);
                    if (string.IsNullOrEmpty(userName))
                    {
                        var userInfo = Context.UserApi.NewInstance();
                        userInfo.UserName = Context.UserApi.IsUserNameExists(displayName)
                            ? Regex.Replace(Convert.ToBase64String(Guid.NewGuid().ToByteArray()), "[/+=]", "")
                            : displayName;
                        userInfo.DisplayName = displayName;
                        userInfo.AvatarUrl   = avatarUrl;
                        userInfo.Gender      = gender;

                        string errorMessage;
                        Context.UserApi.Insert(userInfo, Guid.NewGuid().ToString(), out errorMessage);
                        userName = userInfo.UserName;

                        OAuthDao.Insert(new OAuthInfo
                        {
                            Source   = OAuthType.Qq.Value,
                            UniqueId = uniqueId,
                            UserName = userName
                        });
                    }
                }

                if (!string.IsNullOrEmpty(userName))
                {
                    request.UserLogin(userName, true);
                }

                HttpContext.Current.Response.Redirect(redirectUrl);

                return(Ok());
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
    public void Authenticate_ShouldAllowEmptyConsumerSecret_OnHttpAuthorizationHeaderHandling(OAuthType type)
    {
        // Arrange
        const string url = "https://no-query.string";

        var client  = new RestClient(url);
        var request = new RestRequest();

        _authenticator.Type           = type;
        _authenticator.ConsumerSecret = null;

        // Act
        _authenticator.Authenticate(client, request);

        // Assert
        var authParameter = request.Parameters.Single(x => x.Name == KnownHeaders.Authorization);
        var value         = (string)authParameter.Value;

        Assert.NotNull(value);
        Assert.NotEmpty(value);
        Assert.Contains("OAuth", value !);
        Assert.Contains($"oauth_signature=\"{OAuthTools.UrlEncodeStrict("&")}", value);
    }
Example #14
0
 public static Hammock.Authentication.OAuth.OAuthCredentials createOAuthCredentials(OAuthType type, String strToken, String strSecret, String strVerifier, String strCallBack)
 {
     Hammock.Authentication.OAuth.OAuthCredentials credentials = new Hammock.Authentication.OAuth.OAuthCredentials()
     {
         Type              = type,
         SignatureMethod   = Hammock.Authentication.OAuth.OAuthSignatureMethod.HmacSha1,
         ParameterHandling = Hammock.Authentication.OAuth.OAuthParameterHandling.HttpAuthorizationHeader,
         ConsumerKey       = SampleApp.Sources.democlient.ApiCredentials.CLIENT.key,
         ConsumerSecret    = SampleApp.Sources.democlient.ApiCredentials.CLIENT.secret,
         Token             = strToken,
         TokenSecret       = strSecret,
         Verifier          = strVerifier,
         CallbackUrl       = strCallBack
     };
     return(credentials);
 }
 public Task <string> SignInTo(OAuthType socialType)
 {
     return(Task.FromResult(string.Empty));
 }
        public async Task <ActionResult <GetRedirectResult> > GetRedirect([FromRoute] string type,
                                                                          [FromQuery] GetRedirectRequest request)
        {
            var host      = ApiUtils.GetHost(Request);
            var oAuthType = OAuthType.Parse(type);

            var userName = string.Empty;

            if (oAuthType == OAuthType.Weixin)
            {
                var settings = await _loginManager.GetWeixinSettingsAsync();

                var client = new WeixinClient(settings.WeixinAppId, settings.WeixinAppSecret, host, request.RedirectUrl);

                var userInfo = await client.GetUserInfoAsync(request.Code);

                userName = await _oAuthRepository.GetUserNameAsync(OAuthType.Weixin.Value, userInfo.UnionId);

                if (string.IsNullOrEmpty(userName))
                {
                    var user = new User
                    {
                        UserName = await _userRepository.IsUserNameExistsAsync(userInfo.Nickname)
                            ? Regex.Replace(Convert.ToBase64String(Guid.NewGuid().ToByteArray()), "[/+=]", "")
                            : userInfo.Nickname,
                        DisplayName = userInfo.Nickname,
                        AvatarUrl   = userInfo.HeadImgUrl
                    };

                    var(newUser, _) = await _userRepository.InsertAsync(user, Guid.NewGuid().ToString(), PageUtils.GetIpAddress(Request));

                    userName = newUser.UserName;

                    await _oAuthRepository.InsertAsync(new OAuth
                    {
                        Source   = OAuthType.Weixin.Value,
                        UniqueId = userInfo.UnionId,
                        UserName = userName
                    });
                }
            }
            else if (oAuthType == OAuthType.Qq)
            {
                var settings = await _loginManager.GetQqSettingsAsync();

                var client = new QqClient(settings.QqAppId, settings.QqAppKey, host, request.RedirectUrl);

                var userInfo = await client.GetUserInfoAsync(request.Code);

                userName = await _oAuthRepository.GetUserNameAsync(OAuthType.Qq.Value, userInfo.UniqueId);

                if (string.IsNullOrEmpty(userName))
                {
                    var user = new User
                    {
                        UserName = await _userRepository.IsUserNameExistsAsync(userInfo.DisplayName)
                            ? Regex.Replace(Convert.ToBase64String(Guid.NewGuid().ToByteArray()), "[/+=]", "")
                            : userInfo.DisplayName,
                        DisplayName = userInfo.DisplayName,
                        AvatarUrl   = userInfo.AvatarUrl
                    };

                    var(newUser, _) = await _userRepository.InsertAsync(user, Guid.NewGuid().ToString(), PageUtils.GetIpAddress(Request));

                    userName = newUser.UserName;

                    await _oAuthRepository.InsertAsync(new OAuth
                    {
                        Source   = OAuthType.Qq.Value,
                        UniqueId = userInfo.UniqueId,
                        UserName = userName
                    });
                }
            }
            else if (oAuthType == OAuthType.Weibo)
            {
                var settings = await _loginManager.GetWeiboSettingsAsync();

                var client = new WeiboClient(settings.WeiboAppKey, settings.WeiboAppSecret, host, request.RedirectUrl);

                var userInfo = await client.GetUserInfoAsync(request.Code);

                userName = await _oAuthRepository.GetUserNameAsync(OAuthType.Weibo.Value, userInfo.UnionId);

                if (string.IsNullOrEmpty(userName))
                {
                    var user = new User();
                    user.UserName = await _userRepository.IsUserNameExistsAsync(userInfo.Name)
                        ? Regex.Replace(Convert.ToBase64String(Guid.NewGuid().ToByteArray()), "[/+=]", "")
                        : userInfo.Name;

                    user.DisplayName = userInfo.ScreenName;
                    user.AvatarUrl   = userInfo.AvatarLarge;

                    var(newUser, _) = await _userRepository.InsertAsync(user, Guid.NewGuid().ToString(), PageUtils.GetIpAddress(Request));

                    userName = newUser.UserName;

                    await _oAuthRepository.InsertAsync(new OAuth
                    {
                        Source   = OAuthType.Weibo.Value,
                        UniqueId = userInfo.UnionId,
                        UserName = userName
                    });
                }
            }

            var token = _authManager.AuthenticateUser(await _userRepository.GetByUserNameAsync(userName), true);

            if (oAuthType == OAuthType.Qq || oAuthType == OAuthType.Weibo)
            {
                return(Redirect(PageUtils.AddQueryString(request.RedirectUrl, $"token={token}")));
            }
            else
            {
                return(new GetRedirectResult
                {
                    RedirectUrl = request.RedirectUrl,
                    Token = token
                });
            }
        }