public static async Task TestSetup(TestContext context) { SFApplicationHelper.RegisterServices(); SDKServiceLocator.RegisterService<ILoggingService, Hybrid.Logging.Logger>(); var settings = new EncryptionSettings(new HmacSHA256KeyGenerator()); Encryptor.init(settings); var options = new LoginOptions(TestCredentials.LoginUrl, TestCredentials.ClientId, TestCallbackUrl, "mobile", TestScopes); var response = new AuthResponse { RefreshToken = TestCredentials.RefreshToken, AccessToken = TestAuthToken, InstanceUrl = TestCredentials.InstanceUrl, IdentityUrl = TestCredentials.IdentityUrl, Scopes = TestScopes, }; Account account = await AccountManager.CreateNewAccount(options, response); account.UserId = TestCredentials.UserId; account.UserName = TestCredentials.Username; await OAuth2.RefreshAuthTokenAsync(account); _smartStore = SmartStore.GetSmartStore(); _smartStore.ResetDatabase(); _syncManager = SyncManager.GetInstance(); _restClient = new RestClient(account.InstanceUrl, account.AccessToken, async () => { account = AccountManager.GetAccount(); account = await OAuth2.RefreshAuthTokenAsync(account); return account.AccessToken; } ); CreateAccountsSoup(); _idToNames = await CreateTestAccountsOnServer(CountTestAccounts); }
/// <summary> /// Persist oauth credentials via the AccountManager and navigate back to previous screen /// </summary> /// <param name="loginOptions"></param> /// <param name="authResponse"></param> public async void EndLoginFlow(LoginOptions loginOptions, AuthResponse authResponse) { await AccountManager.CreateNewAccount(loginOptions, authResponse); Frame frame = Window.Current.Content as Frame; frame.Navigate(SalesforceApplication.RootApplicationPage); SalesforcePhoneApplication.ContinuationManager.MarkAsStale(); }
public void SetUp() { var loginOptions = new LoginOptions(TestCredentials.LOGIN_URL, TestCredentials.CLIENT_ID, null, null); _accessToken = OAuth2.RefreshAuthTokenRequest(loginOptions, TestCredentials.REFRESH_TOKEN).Result.AccessToken; _restClient = new RestClient(TestCredentials.INSTANCE_SERVER, _accessToken, null); _unauthenticatedRestClient = new RestClient(TestCredentials.INSTANCE_SERVER); }
/// <summary> /// Persist oauth credentials via the AccountManager /// </summary> /// <param name="loginOptions"></param> /// <param name="authResponse"></param> public async void EndLoginFlow(LoginOptions loginOptions, AuthResponse authResponse) { if (await AccountManager.CreateNewAccount(loginOptions, authResponse)) { Frame frame = Window.Current.Content as Frame; frame.Navigate(SalesforceApplication.RootApplicationPage); } }
/// <summary> /// Constructor /// </summary> public PhoneHybridMainPage() { _instance = this; _syncContext = SynchronizationContext.Current; _bootConfig = BootConfig.GetBootConfig(); _loginOptions = new LoginOptions("https://test.salesforce.com" /* FIXME once we have a server picker */, _bootConfig.ClientId, _bootConfig.CallbackURL, _bootConfig.Scopes); _clientManager = new ClientManager(_loginOptions); }
protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); IDictionary<string, string> qs = NavigationContext.QueryString; _loginOptions = new LoginOptions(qs[AuthHelper.LOGIN_SERVER], qs[AuthHelper.CLIENT_ID], qs[AuthHelper.CALLBACK_URL], qs[AuthHelper.SCOPES].Split(' ')); Uri loginUri = new Uri(OAuth2.ComputeAuthorizationUrl(_loginOptions)); WebBrowser wv = WebViewControl(); wv.Navigating += OnNavigating; wv.Source = loginUri; }
/// <summary> /// Navigate to the /Pages/LoginPage.xaml and load login page in the webview /// </summary> /// <param name="loginOptions"></param> public void StartLoginFlow(LoginOptions loginOptions) { string loginUrl = Uri.EscapeUriString(loginOptions.LoginUrl); string clientId = Uri.EscapeUriString(loginOptions.ClientId); string callbackUrl = Uri.EscapeUriString(loginOptions.CallbackUrl); string scopes = Uri.EscapeUriString(string.Join(" ", loginOptions.Scopes)); string QueryString = string.Format("?{0}={1}&{2}={3}&{4}={5}&{6}={7}", LOGIN_SERVER, loginUrl, CLIENT_ID, clientId, CALLBACK_URL, callbackUrl, SCOPES, scopes); // TODO move LoginPage.xaml to Salesforce.SDK.Phone assembly ((PhoneApplicationFrame) Application.Current.RootVisual).Navigate(new Uri("/Pages/LoginPage.xaml" + QueryString, UriKind.Relative)); }
public void testCallIdentityService() { // Get auth token and identity url (through refresh) LoginOptions loginOptions = new LoginOptions(TestCredentials.LOGIN_URL, TestCredentials.CLIENT_ID, null, null); AuthResponse refreshResponse = OAuth2.RefreshAuthToken(loginOptions, TestCredentials.REFRESH_TOKEN).Result; // Call the identity service IdentityResponse identityResponse = OAuth2.CallIdentityService(refreshResponse.IdentityUrl, refreshResponse.AccessToken).Result; // Check username Assert.AreEqual("*****@*****.**", identityResponse.UserName); }
public void TestComputeAuthorizationUrl() { string loginUrl = "https://login.salesforce.com"; string clientId = "TEST_CLIENT_ID"; string callbackUrl = "test://sfdc"; string[] scopes = { "web", "api" }; LoginOptions loginOptions = new LoginOptions(loginUrl, clientId, callbackUrl, scopes); string expectedUrl = "https://login.salesforce.com/services/oauth2/authorize?display=touch&response_type=token&client_id=TEST_CLIENT_ID&redirect_uri=test://sfdc&scope=web%20api%20refresh_token"; string actualUrl = OAuth2.ComputeAuthorizationUrl(loginOptions); Assert.AreEqual(expectedUrl, actualUrl, "Wrong authorization url"); }
private async void DoAuthFlow(LoginOptions loginOptions) { Uri loginUri = new Uri(OAuth2.ComputeAuthorizationUrl(loginOptions)); Uri callbackUri = new Uri(loginOptions.CallbackUrl); WebAuthenticationResult webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, loginUri, callbackUri) ; if (webAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success) { Uri responseUri = new Uri(webAuthenticationResult.ResponseData.ToString()); AuthResponse authResponse = OAuth2.ParseFragment(responseUri.Fragment.Substring(1)); PlatformAdapter.Resolve<IAuthHelper>().EndLoginFlow(loginOptions, authResponse); } }
/// <summary> /// This should be called when login is complete. A new account is created /// in the AccountManager and the pincode screen is shown if needeed /// </summary> /// <param name="loginOptions"></param> /// <param name="authResponse"></param> public async Task OnLoginCompleteAsync(LoginOptions loginOptions, AuthResponse authResponse) { var frame = Window.Current.Content as Frame; var account = await AccountManager.CreateNewAccount(loginOptions, authResponse); if (account.Policy != null && (!PincodeManager.IsPincodeSet() || AuthStorageHelper.IsPincodeRequired())) { PincodeManager.LaunchPincodeScreen(); } else { SDKServiceLocator.Get<ILoggingService>().Log($"Navigating to {SDKManager.RootApplicationPage}", LoggingLevel.Information); frame?.Navigate(SDKManager.RootApplicationPage); } }
/// <summary> /// Persist oauth credentials via the AccountManager /// </summary> /// <param name="loginOptions"></param> /// <param name="authResponse"></param> public async void EndLoginFlow(LoginOptions loginOptions, AuthResponse authResponse) { var frame = Window.Current.Content as Frame; Account account = await AccountManager.CreateNewAccount(loginOptions, authResponse); if (account.Policy != null && (!PincodeManager.IsPincodeSet() || AuthStorageHelper.IsPincodeRequired())) { PincodeManager.LaunchPincodeScreen(); } else { PlatformAdapter.SendToCustomLogger(string.Format("AuthHelper.EndLoginFlow - Navigating to {0}", SDKManager.RootApplicationPage), LoggingLevel.Information); frame.Navigate(SDKManager.RootApplicationPage); } }
/// <summary> /// Build the URL to the authorization web page for this login server /// You need not provide refresh_token, as it is provided automatically /// </summary> /// <param name="loginOptions"></param> /// <returns>A URL to start the OAuth flow in a web browser/view.</returns> public static string ComputeAuthorizationUrl(LoginOptions loginOptions) { // Scope string scopeStr = string.Join(" ", loginOptions.Scopes.Concat(new[] { RefreshScope }).Distinct().ToArray()); // Args string[] args = { loginOptions.DisplayType, loginOptions.ClientId, loginOptions.CallbackUrl, scopeStr }; object[] urlEncodedArgs = args.Select(WebUtility.UrlEncode).ToArray(); // Authorization url string authorizationUrl = string.Format(loginOptions.LoginUrl + OauthAuthenticationPath + OauthAuthenticationQueryString, urlEncodedArgs); return(authorizationUrl); }
/// <summary> /// Create and persist Account for newly authenticated user /// </summary> /// <param name="loginOptions"></param> /// <param name="authResponse"></param> public async static Task <bool> CreateNewAccount(LoginOptions loginOptions, AuthResponse authResponse) { Account account = new Account(loginOptions.LoginUrl, loginOptions.ClientId, loginOptions.CallbackUrl, loginOptions.Scopes, authResponse.InstanceUrl, authResponse.IdentityUrl, authResponse.AccessToken, authResponse.RefreshToken); var cm = new ClientManager(); var client = cm.PeekRestClient(); IdentityResponse identity = await OAuth2.CallIdentityService(authResponse.IdentityUrl, authResponse.AccessToken); if (identity != null) { account.UserId = identity.UserId; account.UserName = identity.UserName; AuthStorage.PersistCredentials(account); return(true); } return(false); }
/// <summary> /// Persist oauth credentials via the AccountManager and navigate back to previous screen /// </summary> /// <param name="loginOptions"></param> /// <param name="authResponse"></param> public async void EndLoginFlow(LoginOptions loginOptions, AuthResponse authResponse) { Account account = await AccountManager.CreateNewAccount(loginOptions, authResponse); var frame = Window.Current.Content as Frame; if (account.Policy != null && (!PincodeManager.IsPincodeSet() || AuthStorageHelper.IsPincodeRequired())) { PincodeManager.LaunchPincodeScreen(); } else { PlatformAdapter.SendToCustomLogger(string.Format("AuthHelper.EndLoginFlow - Navigating to {0}", SDKManager.RootApplicationPage), LoggingLevel.Information); frame.Navigate(SDKManager.RootApplicationPage); } }
/// <summary> /// Async method to revoke the user's refresh token (i.e. do a server-side logout for the authenticated user) /// </summary> /// <param name="loginOptions"></param> /// <param name="refreshToken"></param> /// <returns>true if successful</returns> public static async Task <bool> RevokeAuthTokenAsync(LoginOptions loginOptions, string refreshToken) { // Args string argsStr = string.Format(OauthRevokeQueryString, new[] { WebUtility.UrlEncode(refreshToken) }); // Revoke url string revokeUrl = loginOptions.LoginUrl + OauthRevokePath; // Post HttpCall c = HttpCall.CreatePost(revokeUrl, argsStr); // ExecuteAsync post HttpCall result = await c.ExecuteAsync().ConfigureAwait(false); LoggingService.Log($"result.StatusCode = {result.StatusCode}", LoggingLevel.Verbose); return(result.StatusCode == HttpStatusCode.OK); }
/// <summary> /// Async method to revoke the user's refresh token (i.e. do a server-side logout for the authenticated user) /// </summary> /// <param name="loginOptions"></param> /// <param name="refreshToken"></param> /// <returns>true if successful</returns> public static async Task <bool> RevokeAuthToken(LoginOptions loginOptions, string refreshToken) { // Args string argsStr = string.Format(OauthRevokeQueryString, new[] { WebUtility.UrlEncode(refreshToken) }); // Revoke url string revokeUrl = loginOptions.LoginUrl + OauthRevokePath; // Post HttpCall c = HttpCall.CreatePost(revokeUrl, argsStr); // Execute post HttpCall result = await c.Execute().ConfigureAwait(false); PlatformAdapter.SendToCustomLogger(string.Format("OAuth2.RevokeAuthToken - result.StatusCode = {0}", result.StatusCode), LoggingLevel.Verbose); return(result.StatusCode == HttpStatusCode.Ok); }
public async static void ClearCookies(LoginOptions loginOptions) { Frame frame = Window.Current.Content as Frame; if (frame != null) { await frame.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { Uri loginUri = new Uri(ComputeAuthorizationUrl(loginOptions)); WebView web = new WebView(); Windows.Web.Http.Filters.HttpBaseProtocolFilter myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter(); var cookieManager = myFilter.CookieManager; Windows.Web.Http.HttpCookieCollection cookies = cookieManager.GetCookies(loginUri); foreach (Windows.Web.Http.HttpCookie cookie in cookies) { cookieManager.DeleteCookie(cookie); } }); } }
/// <summary> /// Persist account, and sets account as the current account. /// </summary> /// <param name="account"></param> internal void PersistCurrentCredentials(Account account) { var userCredentials = SafeRetrieveUser(PasswordVaultAccounts, account.UserName); if (userCredentials != null) { try { LoggingService.Log("removing existing credential", LoggingLevel.Verbose); _vault.Remove(userCredentials); // clear the current account from the password vault var current = _vault.FindAllByResource(PasswordVaultCurrentAccount); if (current != null) { foreach (var user in current) { _vault.Remove(user); } } } catch (Exception) { LoggingService.Log("did not find existing logged in user while persisting", LoggingLevel.Verbose); } } var serialized = EncryptionService.Encrypt(JsonConvert.SerializeObject(account)); if (account.UserName != null) { _vault.Add(new PasswordCredential(PasswordVaultAccounts, account.UserName, serialized)); _vault.Add(new PasswordCredential(PasswordVaultCurrentAccount, account.UserName, serialized)); } var options = new LoginOptions(account.LoginUrl, account.ClientId, account.CallbackUrl, LoginOptions.DefaultDisplayType, account.Scopes); SalesforceConfig.LoginOptions = options; LoggingService.Log("done adding info to vault", LoggingLevel.Verbose); }
/// <summary> /// Persist account, and sets account as the current account. /// </summary> /// <param name="account"></param> internal void PersistCredentials(Account account) { // TODO use PasswordVault ApplicationDataContainer settings = ApplicationData.Current.LocalSettings; Dictionary <string, Account> accounts = RetrievePersistedCredentials(); if (accounts.ContainsKey(account.UserId)) { accounts[account.UserId] = account; } else { accounts.Add(account.UserId, account); } String accountJson = JsonConvert.SerializeObject(accounts); settings.Values[ACCOUNT_SETTING] = Encryptor.Encrypt(accountJson); settings.Values[CURRENT_ACCOUNT] = Encryptor.Encrypt(account.UserId); LoginOptions options = new LoginOptions(account.LoginUrl, account.ClientId, account.CallbackUrl, account.Scopes); SalesforceConfig.LoginOptions = options; }
/// <summary> /// Create and persist Account for newly authenticated user /// </summary> /// <param name="loginOptions"></param> /// <param name="authResponse"></param> public static async Task <Account> CreateNewAccount(LoginOptions loginOptions, AuthResponse authResponse) { PlatformAdapter.SendToCustomLogger("AccountManager.CreateNewAccount - create account object", LoggingLevel.Verbose); var account = new Account(loginOptions.LoginUrl, loginOptions.ClientId, loginOptions.CallbackUrl, loginOptions.Scopes, authResponse.InstanceUrl, authResponse.IdentityUrl, authResponse.AccessToken, authResponse.RefreshToken); account.CommunityId = authResponse.CommunityId; account.CommunityUrl = authResponse.CommunityUrl; IdentityResponse identity = null; try { var cm = new ClientManager(); cm.PeekRestClient(); identity = await OAuth2.CallIdentityService(authResponse.IdentityUrl, authResponse.AccessToken); } catch (JsonException ex) { PlatformAdapter.SendToCustomLogger( "AccountManager.CreateNewAccount - Exception occurred when retrieving account identity:", LoggingLevel.Critical); PlatformAdapter.SendToCustomLogger(ex, LoggingLevel.Critical); Debug.WriteLine("Error retrieving account identity"); } if (identity != null) { account.UserId = identity.UserId; account.UserName = identity.UserName; account.Policy = identity.MobilePolicy; AuthStorageHelper.GetAuthStorageHelper().PersistCredentials(account); } PlatformAdapter.SendToCustomLogger("AccountManager.CreateNewAccount - done", LoggingLevel.Verbose); return(account); }
private void StartLoginFlow(ServerSetting server) { if (server != null) { VisualStateManager.GoToState(this, LoggingUserInViewState, true); SDKManager.ResetClientManager(); SalesforceConfig config = SDKManager.ServerConfiguration; var options = new LoginOptions(server.ServerHost, config.ClientId, config.CallbackUrl, config.Scopes); SalesforceConfig.LoginOptions = new LoginOptions(server.ServerHost, config.ClientId, config.CallbackUrl, config.Scopes); DoAuthFlow(options); } }
private async void DoAuthFlow(LoginOptions loginOptions) { loginOptions.DisplayType = LoginOptions.DefaultStoreDisplayType; var loginUri = new Uri(OAuth2.ComputeAuthorizationUrl(loginOptions)); var callbackUri = new Uri(loginOptions.CallbackUrl); await SDKServiceLocator.Get<IAuthHelper>().ClearCookiesAsync(loginOptions); WebAuthenticationResult webAuthenticationResult = null; var hasWebAuthErrors = false; try { LoggingService.Log("Launching web authentication broker", LoggingLevel.Verbose); webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, loginUri, callbackUri); } // If a bad URI was passed in the user is shown an error message by the WebAuthenticationBroken, when user // taps back arrow we are then thrown a FileNotFoundException, but since user already saw error message we // should just swallow that exception catch (FileNotFoundException) { SetupAccountPage(); return; } catch (Exception ex) { LoggingService.Log("Exception occurred during login flow", LoggingLevel.Critical); LoggingService.Log(ex, LoggingLevel.Critical); hasWebAuthErrors = true; } if (hasWebAuthErrors) { await DisplayErrorDialogAsync(LocalizedStrings.GetString("generic_error")); SetupAccountPage(); return; } if (webAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success) { var responseUri = new Uri(webAuthenticationResult.ResponseData); if (!String.IsNullOrWhiteSpace(responseUri.Query) && responseUri.Query.IndexOf("error", StringComparison.CurrentCultureIgnoreCase) >= 0) { await DisplayErrorDialogAsync(LocalizedStrings.GetString("generic_authentication_error")); SetupAccountPage(); } else { AuthResponse authResponse = OAuth2.ParseFragment(responseUri.Fragment.Substring(1)); await SDKServiceLocator.Get<IAuthHelper>().OnLoginCompleteAsync(loginOptions, authResponse); } } else if (webAuthenticationResult.ResponseStatus == WebAuthenticationStatus.UserCancel) { SetupAccountPage(); } else { await DisplayErrorDialogAsync(LocalizedStrings.GetString("generic_error")); SetupAccountPage(); } }
/// <summary> /// Create and persist Account for newly authenticated user /// </summary> /// <param name="loginOptions"></param> /// <param name="authResponse"></param> public static async Task<Account> CreateNewAccount(LoginOptions loginOptions, AuthResponse authResponse) { PlatformAdapter.SendToCustomLogger("AccountManager.CreateNewAccount - create account object", LoggingLevel.Verbose); var account = new Account(loginOptions.LoginUrl, loginOptions.ClientId, loginOptions.CallbackUrl, loginOptions.Scopes, authResponse.InstanceUrl, authResponse.IdentityUrl, authResponse.AccessToken, authResponse.RefreshToken); account.CommunityId = authResponse.CommunityId; account.CommunityUrl = authResponse.CommunityUrl; var cm = new ClientManager(); cm.PeekRestClient(); IdentityResponse identity = null; try { identity = await OAuth2.CallIdentityService(authResponse.IdentityUrl, authResponse.AccessToken); } catch (JsonException ex) { PlatformAdapter.SendToCustomLogger( "AccountManager.CreateNewAccount - Exception occurred when retrieving account identity:", LoggingLevel.Critical); PlatformAdapter.SendToCustomLogger(ex, LoggingLevel.Critical); Debug.WriteLine("Error retrieving account identity"); } if (identity != null) { account.UserId = identity.UserId; account.UserName = identity.UserName; account.Policy = identity.MobilePolicy; AuthStorageHelper.GetAuthStorageHelper().PersistCredentials(account); } PlatformAdapter.SendToCustomLogger("AccountManager.CreateNewAccount - done", LoggingLevel.Verbose); return account; }
private void addAccount_Click(object sender, RoutedEventArgs e) { SalesforceApplication.ServerConfiguration.SetSelectedServer(listboxServers.SelectedIndex); SalesforceApplication.ResetClientManager(); ServerSetting server = listboxServers.SelectedItem as ServerSetting; SalesforceConfig config = SalesforceApplication.ServerConfiguration; LoginOptions options = new LoginOptions(server.ServerHost, config.ClientId, config.CallbackUrl, config.Scopes); DoAuthFlow(options); }
public static void ClearCookies(LoginOptions loginOptions) { AuthHelper.ClearCookiesAsync(loginOptions); }
/// <summary> /// Build the URL to the authorization web page for this login server /// You need not provide refresh_token, as it is provided automatically /// </summary> /// <param name="loginOptions"></param> /// <returns>A URL to start the OAuth flow in a web browser/view.</returns> public static string ComputeAuthorizationUrl(LoginOptions loginOptions) { // Scope string scopeStr = string.Join(" ", loginOptions.Scopes.Concat(new[] {RefreshScope}).Distinct().ToArray()); // Args string[] args = {loginOptions.DisplayType, loginOptions.ClientId, loginOptions.CallbackUrl, scopeStr}; object[] urlEncodedArgs = args.Select(WebUtility.UrlEncode).ToArray(); // Authorization url string authorizationUrl = string.Format(loginOptions.LoginUrl + OauthAuthenticationPath + OauthAuthenticationQueryString, urlEncodedArgs); return authorizationUrl; }
public void StartLoginFlow(LoginOptions loginOptions) { if (loginOptions == null || String.IsNullOrWhiteSpace(loginOptions.CallbackUrl) || String.IsNullOrWhiteSpace(loginOptions.LoginUrl)) return; try { var loginUri = new Uri(OAuth2.ComputeAuthorizationUrl(loginOptions)); var callbackUri = new Uri(loginOptions.CallbackUrl); WebAuthenticationBroker.AuthenticateAndContinue(loginUri, callbackUri, null, WebAuthenticationOptions.None); } catch (Exception ex) { PlatformAdapter.SendToCustomLogger("AccountPage.StartLoginFlow - Exception occured", LoggingLevel.Critical); PlatformAdapter.SendToCustomLogger(ex, LoggingLevel.Critical); PlatformAdapter.Resolve<IAuthHelper>().StartLoginFlow(); } }
public void TestRefreshAuthToken() { // Try describe without being authenticated, expect 401 Assert.AreEqual(HttpStatusCode.Unauthorized, DoDescribe(null)); // Get auth token (through refresh) LoginOptions loginOptions = new LoginOptions(TestCredentials.LOGIN_URL, TestCredentials.CLIENT_ID, null, null); AuthResponse refreshResponse = OAuth2.RefreshAuthToken(loginOptions, TestCredentials.REFRESH_TOKEN).Result; // Try describe again, expect 200 Assert.AreEqual(HttpStatusCode.OK, DoDescribe(refreshResponse.AccessToken)); }
/// <summary> /// Async method to make the request for a new auth token. Method returns an AuthResponse with the data returned back /// from /// Salesforce. /// </summary> /// <param name="loginOptions"></param> /// <param name="refreshToken"></param> /// <returns></returns> public static async Task<AuthResponse> RefreshAuthTokenRequest(LoginOptions loginOptions, string refreshToken) { PlatformAdapter.SendToCustomLogger("OAuth2.RefreshAuthTokenRequest - attempting to refresh auth token", LoggingLevel.Verbose); // Args string argsStr = string.Format(OauthRefreshQueryString, new[] {loginOptions.ClientId, refreshToken}); // Refresh url string refreshUrl = loginOptions.LoginUrl + OauthRefreshPath; // Post HttpCall c = HttpCall.CreatePost(refreshUrl, argsStr); // Execute post return await c.ExecuteAndDeserialize<AuthResponse>(); }
/// <summary> /// Async method to revoke the user's refresh token (i.e. do a server-side logout for the authenticated user) /// </summary> /// <param name="loginOptions"></param> /// <param name="refreshToken"></param> /// <returns>true if successful</returns> public static async Task<bool> RevokeAuthToken(LoginOptions loginOptions, string refreshToken) { // Args string argsStr = string.Format(OauthRevokeQueryString, new[] {WebUtility.UrlEncode(refreshToken)}); // Revoke url string revokeUrl = loginOptions.LoginUrl + OauthRevokePath; // Post HttpCall c = HttpCall.CreatePost(revokeUrl, argsStr); // Execute post HttpCall result = await c.Execute().ConfigureAwait(false); PlatformAdapter.SendToCustomLogger(string.Format("OAuth2.RevokeAuthToken - result.StatusCode = {0}", result.StatusCode), LoggingLevel.Verbose); return result.StatusCode == HttpStatusCode.Ok; }
public async Task ClearCookiesAsync(LoginOptions options) { if (Window.Current == null) return; var frame = Window.Current.Content as Frame; if (frame != null) { await frame.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { var loginUri = new Uri(OAuth2.ComputeAuthorizationUrl(options)); var myFilter = new HttpBaseProtocolFilter(); HttpCookieManager cookieManager = myFilter.CookieManager; try { LoggingService.Log("attempting to clear cookies", LoggingLevel.Verbose); HttpCookieCollection cookies = cookieManager.GetCookies(loginUri); foreach (HttpCookie cookie in cookies) { cookieManager.DeleteCookie(cookie); } LoggingService.Log("clear cookies done", LoggingLevel.Verbose); } catch (ArgumentException ex) { LoggingService.Log("Exception occurred when clearing cookies", LoggingLevel.Critical); LoggingService.Log(ex, LoggingLevel.Critical); } }); } }
public static async void ClearCookies(LoginOptions loginOptions) { var frame = Window.Current.Content as Frame; if (frame != null) { await frame.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { var loginUri = new Uri(ComputeAuthorizationUrl(loginOptions)); var myFilter = new HttpBaseProtocolFilter(); HttpCookieManager cookieManager = myFilter.CookieManager; try { PlatformAdapter.SendToCustomLogger("OAuth.ClearCookies - attempting at clearing cookies", LoggingLevel.Verbose); HttpCookieCollection cookies = cookieManager.GetCookies(loginUri); foreach (HttpCookie cookie in cookies) { cookieManager.DeleteCookie(cookie); } PlatformAdapter.SendToCustomLogger("OAuth2.ClearCookies - done", LoggingLevel.Verbose); } catch (ArgumentException ex) { PlatformAdapter.SendToCustomLogger("OAuth2.ClearCookies - Exception occurred when clearing cookies:", LoggingLevel.Critical); PlatformAdapter.SendToCustomLogger(ex, LoggingLevel.Critical); Debug.WriteLine("Error clearing cookies"); } }); } }
/// <summary> /// Create and persist Account for newly authenticated user /// </summary> /// <param name="loginOptions"></param> /// <param name="authResponse"></param> public static void CreateNewAccount(LoginOptions loginOptions, AuthResponse authResponse) { Account account = new Account(loginOptions.LoginUrl, loginOptions.ClientId, loginOptions.CallbackUrl, loginOptions.Scopes, authResponse.InstanceUrl, authResponse.AccessToken, authResponse.RefreshToken); PlatformAdapter.Resolve<IAuthStorageHelper>().PersistCredentials(account); }
/// <summary> /// Persist account, and sets account as the current account. /// </summary> /// <param name="account"></param> internal void PersistCurrentCredentials(Account account) { var userCredentials = SafeRetrieveUser(PasswordVaultAccounts, account.UserName); if (userCredentials != null) { LoggingService.Log("removing existing credential", LoggingLevel.Verbose); _vault.Remove(userCredentials); // clear the current account from the password vault try { var current = _vault.FindAllByResource(PasswordVaultCurrentAccount); if (current != null) { foreach (var user in current) { _vault.Remove(user); } } } catch (Exception) { LoggingService.Log("did not find existing logged in user while persisting", LoggingLevel.Verbose); } } var serialized = EncryptionService.Encrypt(JsonConvert.SerializeObject(account)); if (account.UserName != null) { _vault.Add(new PasswordCredential(PasswordVaultAccounts, account.UserName, serialized)); _vault.Add(new PasswordCredential(PasswordVaultCurrentAccount, account.UserName, serialized)); } var options = new LoginOptions(account.LoginUrl, account.ClientId, account.CallbackUrl, LoginOptions.DefaultDisplayType, account.Scopes); SalesforceConfig.LoginOptions = options; LoggingService.Log("done adding info to vault", LoggingLevel.Verbose); }
/// <summary> /// Create and persist Account for newly authenticated user /// </summary> /// <param name="loginOptions"></param> /// <param name="authResponse"></param> public async static Task<bool> CreateNewAccount(LoginOptions loginOptions, AuthResponse authResponse) { Account account = new Account(loginOptions.LoginUrl, loginOptions.ClientId, loginOptions.CallbackUrl, loginOptions.Scopes, authResponse.InstanceUrl, authResponse.IdentityUrl, authResponse.AccessToken, authResponse.RefreshToken); var cm = new ClientManager(); var client = cm.PeekRestClient(); IdentityResponse identity = await OAuth2.CallIdentityService(authResponse.IdentityUrl, authResponse.AccessToken); if (identity != null) { account.UserId = identity.UserId; account.UserName = identity.UserName; AuthStorage.PersistCredentials(account); return true; } return false; }
/// <summary> /// Async method to revoke the user's refresh token (i.e. do a server-side logout for the authenticated user) /// </summary> /// <param name="loginOptions"></param> /// <param name="refreshToken"></param> /// <returns>true if successful</returns> public static async Task<bool> RevokeAuthTokenAsync(LoginOptions loginOptions, string refreshToken) { // Args string argsStr = string.Format(OauthRevokeQueryString, new[] {WebUtility.UrlEncode(refreshToken)}); // Revoke url string revokeUrl = loginOptions.LoginUrl + OauthRevokePath; // Post HttpCall c = HttpCall.CreatePost(revokeUrl, argsStr); // ExecuteAsync post HttpCall result = await c.ExecuteAsync().ConfigureAwait(false); LoggingService.Log($"result.StatusCode = {result.StatusCode}", LoggingLevel.Verbose); return result.StatusCode == HttpStatusCode.OK; }
public static void ClearCookies(LoginOptions loginOptions) { AuthHelper.ClearCookiesAsync(loginOptions); }
/// <summary> /// Persist account, and sets account as the current account. /// </summary> /// <param name="account"></param> internal void PersistCredentials(Account account) { // TODO use PasswordVault ApplicationDataContainer settings = ApplicationData.Current.LocalSettings; Dictionary<string, Account> accounts = RetrievePersistedCredentials(); if (accounts.ContainsKey(account.UserId)) { accounts[account.UserId] = account; } else { accounts.Add(account.UserId, account); } String accountJson = JsonConvert.SerializeObject(accounts); settings.Values[ACCOUNT_SETTING] = Encryptor.Encrypt(accountJson); settings.Values[CURRENT_ACCOUNT] = Encryptor.Encrypt(account.UserId); LoginOptions options = new LoginOptions(account.LoginUrl, account.ClientId, account.CallbackUrl, account.Scopes); SalesforceConfig.LoginOptions = options; }
/// <summary> /// Create and persist Account for newly authenticated user /// </summary> /// <param name="loginOptions"></param> /// <param name="authResponse"></param> public static async Task<Account> CreateNewAccount(LoginOptions loginOptions, AuthResponse authResponse) { LoggingService.Log("Create account object", LoggingLevel.Verbose); var account = new Account( loginOptions.LoginUrl, loginOptions.ClientId, loginOptions.CallbackUrl, loginOptions.Scopes, authResponse.InstanceUrl, authResponse.IdentityUrl, authResponse.AccessToken, authResponse.RefreshToken) { CommunityId = authResponse.CommunityId, CommunityUrl = authResponse.CommunityUrl }; var cm = new ClientManager(); cm.PeekRestClient(); IdentityResponse identity = null; try { identity = await OAuth2.CallIdentityServiceAsync(authResponse.IdentityUrl, authResponse.AccessToken); } catch (JsonException ex) { LoggingService.Log("Exception occurred when retrieving account identity:", LoggingLevel.Critical); LoggingService.Log(ex, LoggingLevel.Critical); Debug.WriteLine("Error retrieving account identity"); } if (identity != null) { account.UserId = identity.UserId; account.UserName = identity.UserName; account.Policy = identity.MobilePolicy; account.OrganizationId = identity.OrganizationId; await AuthStorageHelper.PersistCurrentAccountAsync(account); LoggedInAccount = account; } LoggingService.Log("Finished creating account", LoggingLevel.Verbose); return account; }