/// <summary> /// Extract and initialize access tokens. /// </summary> /// <param name="webAuthResultResponseData">WAB data containing appropriate tokens.</param> /// <returns>Success or failure.</returns> private async Task <bool> ExchangeRequestTokenForAccessTokenAsync(string webAuthResultResponseData) { string query = new Uri(webAuthResultResponseData, UriKind.Absolute).Query; string code = null; foreach (var keyValue in query.Split(new[] { '?', '&' }, StringSplitOptions.RemoveEmptyEntries)) { if (keyValue.StartsWith("code=", StringComparison.OrdinalIgnoreCase)) { code = keyValue.Substring("code=".Length); break; } } if (code == null) { return(false); } string weiboUrl = $"{OAuthBaseUrl}/access_token"; Dictionary <string, string> postData = new Dictionary <string, string> { ["client_id"] = _tokens.AppKey, ["client_secret"] = _tokens.AppSecret, ["grant_type"] = "authorization_code", ["code"] = code, ["redirect_uri"] = _tokens.RedirectUri }; FormUrlEncodedContent postContent = new FormUrlEncodedContent(postData); string data = null; using (HttpResponseMessage response = await _client.PostAsync(weiboUrl, postContent).ConfigureAwait(false)) { data = await response.Content.ReadAsStringAsync().ConfigureAwait(false); } JObject jObject = JObject.Parse(data); string accessToken = jObject["access_token"].ToObject <string>(); if (string.IsNullOrEmpty(accessToken)) { throw new NullReferenceException("The accessToken is null."); } long uid = jObject["uid"].ToObject <long>(); Uid = uid; _tokens.AccessToken = accessToken; _passwordManager.Store(PasswordKey, new PasswordCredential { UserName = "******", Password = accessToken }); await _storageManager.SetAsync(StorageKey, uid.ToString()); return(true); }
/// <summary> /// Log user in to LinkedIn. /// </summary> /// <returns>Boolean indicating login success.</returns> public async Task <bool> LoginAsync() { var user = _storageManager.Get(LinkedInConstants.STORAGEKEYUSER); var credential = _passwordManager.Get(LinkedInConstants.STORAGEKEYACCESSTOKEN); if (!string.IsNullOrEmpty(user) && credential != null) { Tokens.AccessToken = credential.Password; Username = _storageManager.Get(LinkedInConstants.STORAGEKEYUSER); LoggedIn = true; return(true); } string authorizeCode = await GetAuthorizeCodeAsync(Tokens, RequiredPermissions); if (!string.IsNullOrEmpty(authorizeCode)) { var accessToken = await GetAccessTokenAsync(Tokens, authorizeCode); if (!string.IsNullOrEmpty(accessToken)) { Tokens.AccessToken = accessToken; _passwordManager.Store(LinkedInConstants.STORAGEKEYACCESSTOKEN, new PasswordCredential { UserName = LinkedInConstants.STORAGEKEYUSER, Password = accessToken }); _storageManager.Set(LinkedInConstants.STORAGEKEYUSER, LinkedInConstants.STORAGEKEYUSER); return(true); } } LoggedIn = false; return(false); }
/// <summary> /// Extract and initialize access tokens. /// </summary> /// <param name="webAuthResultResponseData">WAB data containing appropriate tokens.</param> /// <returns>Success or failure.</returns> private async Task <bool> ExchangeRequestTokenForAccessTokenAsync(string webAuthResultResponseData) { string responseData = webAuthResultResponseData.Substring(webAuthResultResponseData.IndexOf("oauth_token")); string requestToken = ExtractTokenFromResponse(responseData, TwitterOAuthTokenType.OAuthRequestOrAccessToken); // Ensure requestToken matches accessToken per Twitter documentation. if (requestToken != _tokens.RequestToken) { return(false); } string oAuthVerifier = ExtractTokenFromResponse(responseData, TwitterOAuthTokenType.OAuthVerifier); string twitterUrl = $"{OAuthBaseUrl}/access_token"; string timeStamp = GetTimeStamp(); string nonce = GetNonce(); string sigBaseStringParams = GetSignatureBaseStringParams(_tokens.ConsumerKey, nonce, timeStamp, "oauth_token=" + requestToken); string sigBaseString = "POST&"; sigBaseString += Uri.EscapeDataString(twitterUrl) + "&" + Uri.EscapeDataString(sigBaseStringParams); string signature = _signatureManager.GetSignature(sigBaseString, _tokens.ConsumerSecret); string data = null; string authorizationHeaderParams = "oauth_consumer_key=\"" + _tokens.ConsumerKey + "\", oauth_nonce=\"" + nonce + "\", oauth_signature_method=\"HMAC-SHA1\", oauth_signature=\"" + Uri.EscapeDataString(signature) + "\", oauth_timestamp=\"" + timeStamp + "\", oauth_token=\"" + Uri.EscapeDataString(requestToken) + "\", oauth_verifier=\"" + Uri.EscapeUriString(oAuthVerifier) + "\" , oauth_version=\"1.0\""; using (var request = new HttpRequestMessage(HttpMethod.Post, new Uri(twitterUrl))) { request.Headers.Authorization = new AuthenticationHeaderValue("OAuth", authorizationHeaderParams); using (var response = await _client.SendAsync(request).ConfigureAwait(false)) { data = await response.Content.ReadAsStringAsync().ConfigureAwait(false); } } var screenName = ExtractTokenFromResponse(data, TwitterOAuthTokenType.ScreenName); var accessToken = ExtractTokenFromResponse(data, TwitterOAuthTokenType.OAuthRequestOrAccessToken); var accessTokenSecret = ExtractTokenFromResponse(data, TwitterOAuthTokenType.OAuthRequestOrAccessTokenSecret); UserScreenName = screenName; _tokens.AccessToken = accessToken; _tokens.AccessTokenSecret = accessTokenSecret; _passwordManager.Store("TwitterAccessToken", new PasswordCredential { UserName = accessToken, Password = accessTokenSecret }); _storageManager.Set("TwitterScreenName", screenName); return(true); }