internal static string GetRefreshedToken(OAuth20Token token)
        {
            if (token.IsExpired)
            {
                try
                {
                    Log.Info("DocuSign refresh token for user " + SecurityContext.CurrentAccount.ID);

                    var refreshed = DocuSignLoginProvider.Instance.RefreshToken(token.RefreshToken);

                    if (refreshed != null)
                    {
                        token.AccessToken  = refreshed.AccessToken;
                        token.RefreshToken = refreshed.RefreshToken;
                        token.ExpiresIn    = refreshed.ExpiresIn;
                        token.Timestamp    = DateTime.UtcNow;

                        SaveToken(token);
                    }
                }
                catch (Exception ex)
                {
                    Log.Error("DocuSign refresh token for user " + SecurityContext.CurrentAccount.ID, ex);
                }
            }
            return(token.AccessToken);
        }
Beispiel #2
0
        private void ImportContacts(OAuth20Token token)
        {
            var response = RequestContacts(token);

            if (response != null && response.Connections != null)
            {
                foreach (var contact in response.Connections)
                {
                    string name = null;
                    if (contact.Names != null)
                    {
                        var first = contact.Names.FirstOrDefault(contactName => !string.IsNullOrEmpty(contactName.displayName));
                        if (first != null)
                        {
                            name = first.displayName;
                        }
                    }
                    string email = null;
                    if (contact.EmailAddresses != null)
                    {
                        var first = contact.EmailAddresses.FirstOrDefault(contactEmail => !string.IsNullOrEmpty(contactEmail.value));
                        if (first != null)
                        {
                            email = first.value;
                        }
                    }

                    Master.AddContactInfo(name, email);
                }
            }
        }
        private static DocuSignAccount GetDocuSignAccount(OAuth20Token token)
        {
            if (token == null)
            {
                throw new ArgumentNullException("token");
            }

            var userInfoString = RequestHelper.PerformRequest(DocuSignLoginProvider.Instance.DocuSignHost + "/oauth/userinfo",
                                                              headers: new Dictionary <string, string> {
                { "Authorization", "Bearer " + DocuSignToken.GetRefreshedToken(token) }
            });

            Log.Debug("DocuSing userInfo: " + userInfoString);

            var userInfo = (DocuSignUserInfo)JsonConvert.DeserializeObject(userInfoString, typeof(DocuSignUserInfo));

            if (userInfo.Accounts == null || userInfo.Accounts.Count == 0)
            {
                throw new Exception("Account is null");
            }

            var account = userInfo.Accounts[0];

            return(account);
        }
        private static LoginProfile RequestProfile(OAuth20Token token)
        {
            var vkProfile    = RequestHelper.PerformRequest(VKProfileUrl + "?access_token=" + token.AccessToken);
            var loginProfile = ProfileFromVK(vkProfile);

            return(loginProfile);
        }
        public OAuth20Token RefreshToken(string refreshToken)
        {
            if (string.IsNullOrEmpty(refreshToken) || string.IsNullOrEmpty(ClientID) || string.IsNullOrEmpty(ClientSecret))
            {
                throw new ArgumentException("Can not refresh given token");
            }

            var data    = string.Format("grant_type=refresh_token&refresh_token={0}", refreshToken);
            var headers = new Dictionary <string, string> {
                { "Authorization", AuthHeader }
            };

            var json = RequestHelper.PerformRequest(AccessTokenUrl, "application/x-www-form-urlencoded", "POST", data, headers);

            if (json == null)
            {
                throw new Exception("Can not get token");
            }

            var refreshed = OAuth20Token.FromJson(json);

            refreshed.ClientID     = ClientID;
            refreshed.ClientSecret = ClientSecret;
            refreshed.RedirectUri  = RedirectUri;
            refreshed.RefreshToken ??= refreshToken;
            return(refreshed);
        }
        public void Open(OAuth20Token token)
        {
            if (IsOpened)
            {
                return;
            }
            _token = token ?? throw new UnauthorizedAccessException("Cannot create GoogleDrive session with given token");

            var tokenResponse = new TokenResponse
            {
                AccessToken      = _token.AccessToken,
                RefreshToken     = _token.RefreshToken,
                IssuedUtc        = _token.Timestamp,
                ExpiresInSeconds = _token.ExpiresIn,
                TokenType        = "Bearer"
            };

            var apiCodeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = new ClientSecrets
                {
                    ClientId     = _token.ClientID,
                    ClientSecret = _token.ClientSecret
                },
                Scopes = new[] { DriveService.Scope.Drive }
            });

            _driveService = new DriveService(new BaseClientService.Initializer
            {
                HttpClientInitializer = new UserCredential(apiCodeFlow, string.Empty, tokenResponse)
            });

            IsOpened = true;
        }
        private static LoginProfile RequestProfile(OAuth20Token token)
        {
            var yandexProfile = RequestHelper.PerformRequest(YandexProfileUrl + "?format=json&oauth_token=" + token.AccessToken);
            var loginProfile  = ProfileFromYandex(yandexProfile);

            return(loginProfile);
        }
Beispiel #8
0
        private OAuth20Token GetAccessToken(string state, string code)
        {
            var timestamp = DateTime.UtcNow.ToString("yyyy.MM.dd HH:mm:ss +0000");

            var msg = Scopes + timestamp + ClientID + state;
            var encodedSignature = SignMsg(msg);
            var clientSecret     = WebEncoders.Base64UrlEncode(encodedSignature);

            var requestParams = new Dictionary <string, string>
            {
                { "client_id", ClientID },
                { "code", code },
                { "grant_type", "authorization_code" },
                { "client_secret", clientSecret },
                { "state", state },
                { "redirect_uri", RedirectUri },
                { "scope", Scopes },
                { "timestamp", timestamp },
                { "token_type", "Bearer" }
            };
            var requestQuery = string.Join("&", requestParams.Select(pair => pair.Key + "=" + HttpUtility.UrlEncode(pair.Value)));

            var result = RequestHelper.PerformRequest(AccessTokenUrl, "application/x-www-form-urlencoded", "POST", requestQuery);

            return(OAuth20Token.FromJson(result));
        }
Beispiel #9
0
        public static OAuth20Token RefreshToken(string requestUrl, OAuth20Token token)
        {
            if (token == null || !CanRefresh(token))
            {
                throw new ArgumentException("Can not refresh given token", "token");
            }

            var data = string.Format("client_id={0}&client_secret={1}&refresh_token={2}&grant_type=refresh_token",
                                     HttpUtility.UrlEncode(token.ClientID),
                                     HttpUtility.UrlEncode(token.ClientSecret),
                                     HttpUtility.UrlEncode(token.RefreshToken));

            var json = RequestHelper.PerformRequest(requestUrl, "application/x-www-form-urlencoded", "POST", data);

            if (json != null)
            {
                var refreshed = OAuth20Token.FromJson(json);
                refreshed.ClientID     = token.ClientID;
                refreshed.ClientSecret = token.ClientSecret;
                refreshed.RedirectUri  = token.RedirectUri;
                refreshed.RefreshToken ??= token.RefreshToken;
                return(refreshed);
            }

            return(token);
        }
Beispiel #10
0
 public static void DeleteToken(OAuth20Token token)
 {
     if (token == null)
     {
         throw new ArgumentNullException("token");
     }
     Token.DeleteToken(AppAttr);
 }
Beispiel #11
0
 public static void SaveToken(OAuth20Token token)
 {
     if (token == null)
     {
         throw new ArgumentNullException("token");
     }
     Token.SaveToken(new Token(token, AppAttr));
 }
Beispiel #12
0
        public XDocument RequestContacts(OAuth20Token token)
        {
            var response = RequestHelper.PerformRequest(GoogleLoginProvider.GoogleUrlContacts, headers: new Dictionary <string, string> {
                { "Authorization", "Bearer " + token.AccessToken }
            });

            return(XDocument.Parse(response));
        }
Beispiel #13
0
        private static LoginProfile RequestProfile(OAuth20Token token)
        {
            var googleProfile = RequestHelper.PerformRequest(GoogleProfileUrl + "me", headers: new Dictionary <string, string> {
                { "Authorization", "Bearer " + token.AccessToken }
            });
            var loginProfile = ProfileFromGoogle(googleProfile);

            return(loginProfile);
        }
Beispiel #14
0
        public static OAuth20Token GetAccessToken <T>(ConsumerFactory consumerFactory, string authCode) where T : Consumer, IOAuthProvider, new()
        {
            var loginProvider = consumerFactory.Get <T>();
            var requestUrl    = loginProvider.AccessTokenUrl;
            var clientID      = loginProvider.ClientID;
            var clientSecret  = loginProvider.ClientSecret;
            var redirectUri   = loginProvider.RedirectUri;

            if (string.IsNullOrEmpty(authCode))
            {
                throw new ArgumentNullException("authCode");
            }
            if (string.IsNullOrEmpty(clientID))
            {
                throw new ArgumentNullException("clientID");
            }
            if (string.IsNullOrEmpty(clientSecret))
            {
                throw new ArgumentNullException("clientSecret");
            }

            var data = string.Format("code={0}&client_id={1}&client_secret={2}",
                                     HttpUtility.UrlEncode(authCode),
                                     HttpUtility.UrlEncode(clientID),
                                     HttpUtility.UrlEncode(clientSecret));

            if (!string.IsNullOrEmpty(redirectUri))
            {
                data += "&redirect_uri=" + HttpUtility.UrlEncode(redirectUri);
            }

            data += "&grant_type=authorization_code";

            var json = RequestHelper.PerformRequest(requestUrl, "application/x-www-form-urlencoded", "POST", data);

            if (json != null)
            {
                if (!json.StartsWith("{"))
                {
                    json = "{\"" + json.Replace("=", "\":\"").Replace("&", "\",\"") + "\"}";
                }

                var token = OAuth20Token.FromJson(json);
                if (token == null)
                {
                    return(null);
                }

                token.ClientID     = clientID;
                token.ClientSecret = clientSecret;
                token.RedirectUri  = redirectUri;
                return(token);
            }

            return(null);
        }
Beispiel #15
0
        protected GoogleContacts RequestContacts(OAuth20Token token)
        {
            var response = RequestHelper.PerformRequest(GoogleLoginProvider.GoogleUrlContacts, headers: new Dictionary <string, string> {
                { "Authorization", "Bearer " + token.AccessToken }
            });

            var contacts = JsonConvert.DeserializeObject <GoogleContacts>(response);

            return(contacts);
        }
        private static string GetUid(OAuth20Token token)
        {
            if (string.IsNullOrEmpty(token.OriginJson))
            {
                return(null);
            }
            var parser = JObject.Parse(token.OriginJson);

            return
                (parser?.Value <string>("x_mailru_vid"));
        }
Beispiel #17
0
        public override ICloudStorageAccessToken LoadToken(Dictionary <String, String> tokendata)
        {
            var type = tokendata[CloudStorage.TokenCredentialType];

            if (type.Equals(typeof(OAuth20Token).ToString()))
            {
                var json = tokendata[SkyDriveConstants.SerializedDataKey];
                return(OAuth20Token.FromJson(json));
            }
            return(null);
        }
Beispiel #18
0
        public void Open(OAuth20Token token)
        {
            if (IsOpened)
            {
                return;
            }

            _token = token;

            IsOpened = true;
        }
        public override LoginProfile GetLoginProfile(OAuth20Token token)
        {
            if (token == null)
            {
                throw new Exception("Login failed");
            }

            var claims = ValidateIdToken(JObject.Parse(token.OriginJson).Value <string>("id_token"));

            return(GetProfileFromClaims(claims));
        }
        public DropboxStorage CreateStorage(OAuth20Token token)
        {
            if (Storage != null && Storage.IsOpened)
            {
                return(Storage);
            }

            var dropboxStorage = new DropboxStorage();

            dropboxStorage.Open(token);
            return(Storage = dropboxStorage);
        }
        public void Open(OAuth20Token token)
        {
            if (IsOpened)
            {
                return;
            }

            _token = token;

            _dropboxClient = new DropboxClient(_token.AccessToken);

            IsOpened = true;
        }
        private static string GetMail(OAuth20Token token)
        {
            if (string.IsNullOrEmpty(token.OriginJson))
            {
                return(null);
            }
            var parser = JObject.Parse(token.OriginJson);

            return
                (parser == null
                    ? null
                    : parser.Value <string>("email"));
        }
Beispiel #23
0
        private void CheckToken()
        {
            if (_token == null)
            {
                throw new UnauthorizedAccessException("Cannot create Box session with given token");
            }
            if (_token.IsExpired)
            {
                _token = OAuth20TokenHelper.RefreshToken(BoxLoginProvider.BoxOauthTokenUrl, _token);

                using (var dbDao = new CachedProviderAccountDao(CoreContext.TenantManager.GetCurrentTenant().TenantId, FileConstant.DatabaseId))
                {
                    dbDao.UpdateProviderInfo(ID, new AuthData(token: _token.ToJson()));
                }
            }
        }
        public void Open(OAuth20Token token)
        {
            if (IsOpened)
            {
                return;
            }

            _token = token;

            var config  = new BoxConfig(_token.ClientID, _token.ClientSecret, new Uri(_token.RedirectUri));
            var session = new OAuthSession(_token.AccessToken, _token.RefreshToken, (int)_token.ExpiresIn, "bearer");

            _boxClient = new BoxClient(config, session);

            IsOpened = true;
        }
Beispiel #25
0
        public static OAuth20Token GetAccessToken(string requestUrl, string clientID, string clientSecret, string redirectUri, string authCode)
        {
            if (String.IsNullOrEmpty(authCode))
            {
                throw new ArgumentNullException("authCode");
            }
            if (String.IsNullOrEmpty(clientID))
            {
                throw new ArgumentNullException("clientID");
            }
            if (String.IsNullOrEmpty(clientSecret))
            {
                throw new ArgumentNullException("clientSecret");
            }

            var data = string.Format("code={0}&client_id={1}&client_secret={2}", authCode, clientID, clientSecret);

            if (!String.IsNullOrEmpty(redirectUri))
            {
                data += "&redirect_uri=" + redirectUri;
            }

            data += "&grant_type=authorization_code";

            var json = RequestHelper.PerformRequest(requestUrl, "application/x-www-form-urlencoded", "POST", data);

            if (json != null)
            {
                if (!json.StartsWith("{"))
                {
                    json = "{\"" + json.Replace("=", "\":\"").Replace("&", "\",\"") + "\"}";
                }

                var token = OAuth20Token.FromJson(json);
                if (token == null)
                {
                    return(null);
                }

                token.ClientID     = clientID;
                token.ClientSecret = clientSecret;
                token.RedirectUri  = redirectUri;
                return(token);
            }

            return(null);
        }
        public OAuth20Token GetAccessToken(string authCode)
        {
            if (string.IsNullOrEmpty(authCode))
            {
                throw new ArgumentNullException("authCode");
            }
            if (string.IsNullOrEmpty(ClientID))
            {
                throw new ArgumentException("clientID");
            }
            if (string.IsNullOrEmpty(ClientSecret))
            {
                throw new ArgumentException("clientSecret");
            }

            var data    = string.Format("grant_type=authorization_code&code={0}", authCode);
            var headers = new Dictionary <string, string> {
                { "Authorization", AuthHeader }
            };

            var json = RequestHelper.PerformRequest(AccessTokenUrl, "application/x-www-form-urlencoded", "POST", data, headers);

            if (json == null)
            {
                throw new Exception("Can not get token");
            }

            if (!json.StartsWith("{"))
            {
                json = "{\"" + json.Replace("=", "\":\"").Replace("&", "\",\"") + "\"}";
            }

            var token = OAuth20Token.FromJson(json);

            if (token == null)
            {
                return(null);
            }

            token.ClientID     = ClientID;
            token.ClientSecret = ClientSecret;
            token.RedirectUri  = RedirectUri;
            return(token);
        }
Beispiel #27
0
        private void ImportContacts(OAuth20Token token)
        {
            var doc = RequestContacts(token);

            //selecting from xdocument
            var contacts = from e in doc.Root.Elements("{http://www.w3.org/2005/Atom}entry")
                           select new
            {
                Name  = e.Element("{http://www.w3.org/2005/Atom}title").Value,
                Email = from a in e.Elements("{http://schemas.google.com/g/2005}email")
                        where a.Attribute("address") != null
                        select a.Attribute("address").Value
            };

            foreach (var contact in contacts)
            {
                Master.AddContactInfo(contact.Name, contact.Email);
            }
        }
        public static OAuth20Token RefreshToken(string requestUrl, OAuth20Token token)
        {
            if (token == null || !CanRefresh(token)) throw new ArgumentException("Can not refresh given token", "token");

            var data = String.Format("client_id={0}&client_secret={1}&redirect_uri={2}&grant_type=refresh_token&refresh_token={3}",
                                     token.ClientID, token.ClientSecret, token.RedirectUri, token.RefreshToken);

            var json = RequestHelper.PerformRequest(requestUrl, "application/x-www-form-urlencoded", "POST", data);
            if (json != null)
            {
                var refreshed = OAuth20Token.FromJson(json);
                refreshed.ClientID = token.ClientID;
                refreshed.ClientSecret = token.ClientSecret;
                refreshed.RedirectUri = token.RedirectUri;
                return refreshed;
            }

            return token;
        }
        private void ImportContacts(OAuth20Token token)
        {
            var doc = RequestContacts(token);

            //selecting from xdocument
            var contacts = doc.Root.Elements("{http://www.w3.org/2005/Atom}entry")
                           .Select(e => new
            {
                Name  = e.Element("{http://www.w3.org/2005/Atom}title").Value,
                Email = e.Elements("{http://schemas.google.com/g/2005}email")
                        .Where(a => a.Attribute("address") != null)
                        .Select(a => a.Attribute("address").Value)
                        .FirstOrDefault()
            }).ToList();

            foreach (var contact in contacts)
            {
                Master.AddContactInfo(contact.Name, contact.Email);
            }
        }
Beispiel #30
0
        public GoogleDriveProviderInfo(int id, string providerKey, string customerTitle, string token, Guid owner, FolderType rootFolderType, DateTime createOn)
        {
            if (string.IsNullOrEmpty(providerKey))
            {
                throw new ArgumentNullException("providerKey");
            }
            if (string.IsNullOrEmpty(token))
            {
                throw new ArgumentException("Token can't be null");
            }

            ID            = id;
            CustomerTitle = customerTitle;
            Owner         = owner == Guid.Empty ? SecurityContext.CurrentAccount.ID : owner;

            ProviderKey     = providerKey;
            _token          = OAuth20Token.FromJson(token);
            _rootFolderType = rootFolderType;
            _createOn       = createOn;
        }
        public OAuth20Token RequestAccessToken(string refreshToken)
        {
            var token = new OAuth20Token
            {
                ClientID     = ClientId,
                ClientSecret = ClientSecret,
                RedirectUri  = RedirectUrl,
                RefreshToken = refreshToken,
            };

            try
            {
                return(OAuth20TokenHelper.RefreshToken(RefreshUrl, token));
            }
            catch (Exception ex)
            {
                log.Error("RequestAccessToken() Exception:\r\n{0}\r\n", ex.ToString());
                return(null);
            }
        }
        private static LoginProfile RequestProfile(OAuth20Token token)
        {
            var vkProfile = RequestHelper.PerformRequest(VKProfileUrl + "?access_token=" + token.AccessToken);
            var loginProfile = ProfileFromVK(vkProfile);

            return loginProfile;
        }
 private static bool CanRefresh(OAuth20Token token)
 {
     return !String.IsNullOrEmpty(token.ClientID) && !String.IsNullOrEmpty(token.ClientSecret) && !String.IsNullOrEmpty(token.RedirectUri);
 }
        private static LoginProfile RequestProfile(OAuth20Token token)
        {
            var yandexProfile = RequestHelper.PerformRequest(YandexProfileUrl + "?format=json&oauth_token=" + token.AccessToken);
            var loginProfile = ProfileFromYandex(yandexProfile);

            return loginProfile;
        }