private async Task RefreshCredentialsAsync(GoogleCredentials credentials) { var clientId = apiKeyRepository.GetClientId(); var clientSecret = apiKeyRepository.GetClientSecret(); var url = new StringBuilder(); url.Append("https://oauth2.googleapis.com/token?"); url.Append($"client_id={clientId}&"); url.Append($"client_secret={clientSecret}&"); url.Append($"refresh_token={UrlEncode(credentials.RefreshToken)}&"); url.Append($"grant_type=refresh_token"); var responseMessage = await httpClient.PostAsync(url.ToString(), null); responseMessage.EnsureSuccessStatusCode(); var response = JsonConvert.DeserializeObject <JObject>( await responseMessage.Content.ReadAsStringAsync() ); var accessToken = response.Value <string>("access_token"); var expirySeconds = response.Value <int>("expires_in"); var expiry = DateTime.Now + TimeSpan.FromSeconds(expirySeconds - 5); credentials.AccessToken = accessToken; credentials.AccessTokenExpiry = expiry; }
private byte[] BuildMTalkRequest(GoogleCredentials googleCredentials) { var idStringBytes = Encoding.ASCII.GetBytes(googleCredentials.Id.ToString()); var idLen = VarInt.Write(idStringBytes.Length).ToList(); var tokenStringByes = Encoding.ASCII.GetBytes(googleCredentials.Token.ToString()); var tokenLen = VarInt.Write(tokenStringByes.Length).ToList(); var hexId = "android-" + BitConverter.ToString(googleCredentials.RawId.ToArray()).Replace("-", string.Empty).ToLowerInvariant(); var hexIdBytes = Encoding.ASCII.GetBytes(hexId); var hexIdLen = VarInt.Write(hexIdBytes.Length); var body = message1 .Concat(idLen) .Concat(idStringBytes) .Concat(message2) .Concat(idLen) .Concat(idStringBytes) .Concat(message3) .Concat(tokenLen) .Concat(tokenStringByes) .Concat(message4) .Concat(hexIdLen) .Concat(hexIdBytes) .Concat(message5) .ToList(); var bodyLen = VarInt.Write(body.Count); return(message6 .Concat(bodyLen) .Concat(body) .ToArray()); }
public void SendRequest(GoogleCredentials googleCredentials, ILog log) { log.Debug($"mtalk build request"); var request = BuildMTalkRequest(googleCredentials); log.Debug($"mtalk tcp connect"); using (var tcpClient = new TcpClient(Host, Port)) { using (var sslStream = new SslStream(tcpClient.GetStream(), false, (sender, certificate, chain, errors) => true, null)) { log.Debug($"mtalk ssl authenticate"); sslStream.AuthenticateAsClient(Host); log.Debug($"mtalk send request"); sslStream.Write(request); sslStream.Flush(); log.Debug($"mtalk read response"); sslStream.ReadByte(); var responseCode = sslStream.ReadByte(); if (responseCode != SuccessCode) { throw new InvalidOperationException($"MTalk expected response code [{SuccessCode}], got [{responseCode}]"); } } } }
public void PopulateProviderCredentials_Google_CreatesExpectedCredentials() { const string UserIdClaimValue = "GoogleId"; GoogleCredentials credentials = new GoogleCredentials(); TokenResult tokenResult = new TokenResult(); tokenResult.Properties.Add(TokenResult.Authentication.AccessTokenName, "TestAccessToken"); tokenResult.Properties.Add(TokenResult.Authentication.RefreshTokenName, "TestRefreshToken"); tokenResult.Properties.Add("AccessTokenExpiration", "2015-03-12T16:49:28.504Z"); Dictionary <string, string> claims = new Dictionary <string, string> { { "Claim1", "Value1" }, { "Claim2", "Value1" }, { "Claim3", "Value1" }, { ClaimTypes.NameIdentifier, UserIdClaimValue } }; tokenResult.Claims = claims; MobileAppUser.PopulateProviderCredentials(tokenResult, credentials); Assert.Equal("TestAccessToken", credentials.AccessToken); Assert.Equal("TestRefreshToken", credentials.RefreshToken); Assert.Equal(DateTimeOffset.Parse("2015-03-12T16:49:28.504Z"), credentials.AccessTokenExpiration); Assert.Equal(UserIdClaimValue, credentials.UserId); Assert.Equal(claims.Count, credentials.Claims.Count); }
public void PopulateProviderCredentials_Google_CreatesExpectedCredentials() { const string UserIdClaimValue = "GoogleId"; GoogleCredentials credentials = new GoogleCredentials(); TokenEntry tokenEntry = new TokenEntry("google"); tokenEntry.AccessToken = "TestAccessToken"; tokenEntry.RefreshToken = "TestRefreshToken"; tokenEntry.ExpiresOn = DateTime.Parse("2015-03-12T16:49:28.504Z"); List <ClaimSlim> claims = new List <ClaimSlim> { new ClaimSlim("Claim1", "Value1"), new ClaimSlim("Claim2", "Value2"), new ClaimSlim("Claim3", "Value3"), }; tokenEntry.UserClaims = claims; tokenEntry.UserId = UserIdClaimValue; IPrincipalExtensions.PopulateProviderCredentials(tokenEntry, credentials); Assert.Equal("TestAccessToken", credentials.AccessToken); Assert.Equal("TestRefreshToken", credentials.RefreshToken); Assert.Equal(DateTimeOffset.Parse("2015-03-12T16:49:28.504Z"), credentials.AccessTokenExpiration); Assert.Equal(UserIdClaimValue, credentials.UserId); Assert.Equal(claims.Count, credentials.Claims.Count); Assert.Equal(claims.Count, credentials.UserClaims.Count()); }
public GooglePaintingsController() { _databaseContext = new DatabaseContext(); using (var certificateStream = GetEmbeddedResourceStream <MvcApplication>("google-cloud-storage-privatekey.p12")) { _credentials = new GoogleCredentials("*****@*****.**", certificateStream, "foobarbaz"); } }
internal static Task <UserCredential> AuthorizeAsync(GoogleCredentials googleCredentials) { return(GoogleWebAuthorizationBroker.AuthorizeAsync( new ClientSecrets { ClientId = googleCredentials.ClientId, ClientSecret = googleCredentials.ClientSecret }, new[] { SheetsService.Scope.SpreadsheetsReadonly, GmailService.Scope.GmailReadonly }, "user", default,
public void LogIn_Login_and_password_are_valid_doc_is_absent_CredentialsException() { //arrange GoogleCredentials target = CreateGoogleCredentials("aaaaaaaaaaaaaa"); //act and throw Assert.Throws <CredentialsException>(() => target.LogIn("*****@*****.**", "MemorizeIt"), "spreadsheet is absent"); }
public void LogIn_Login_and_password_invalid_CredentialsException() { //arrange GoogleCredentials target = CreateGoogleCredentials(); //act and throw Assert.Throws <CredentialsException>(() => target.LogIn("fake", "invalid password"), "Invalid credentials"); }
public Spreadsheet CreateSpreadSheet(GoogleCredentials googleCredentials, System.Security.Claims.ClaimsPrincipal user, CreateRequest createRequest) { UserCredential credential; var userMail = user.Claims.FirstOrDefault(claim => claim.Value.Contains("@"))?.Value ?? "user"; using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { var credPath = "token.json"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, _scopes, userMail, CancellationToken.None, new FileDataStore(credPath, true)).Result; } // Create Google Sheets API service. var service = new SheetsService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "creatingcompetitionlists", }); var myNewSheet = new Spreadsheet { Properties = new SpreadsheetProperties { Title = createRequest.TableName }, Sheets = new List <Sheet> { new Sheet { Properties = new SheetProperties { Title = "БАЗА" } } } }; foreach (var directionId in createRequest.DirectionIds.Select(int.Parse)) { using var db = new competition_listContext(); myNewSheet.Sheets.Add(new Sheet { Properties = new SheetProperties { Title = db.Directions.FirstOrDefault(x => x.Id == directionId)?.ShortTitle } }); } myNewSheet.Sheets.Add(new Sheet { Properties = new SheetProperties { Title = "ЧИСЛО МЕСТ" } }); return(service.Spreadsheets.Create(myNewSheet).Execute()); }
private async Task <string> GetOrCreateFolder(string clientId, string clientSecret, string refreshToken) { var googleCredentials = new GoogleCredentials { ClientId = clientId, ClientSecret = clientSecret, RefreshToken = refreshToken }; return(await _googleDriveService.GetOrCreateFolder(Constants.GoogleDriveFolderName, null, googleCredentials, CancellationToken.None)); }
private async Task<string> GetOrCreateFolder(string clientId, string clientSecret, string refreshToken) { var googleCredentials = new GoogleCredentials { ClientId = clientId, ClientSecret = clientSecret, RefreshToken = refreshToken }; return await _googleDriveService.GetOrCreateFolder(Constants.GoogleDriveFolderName, null, googleCredentials, CancellationToken.None); }
public async Task <string> GetAccessToken(GoogleCredentials entityCredentials) { if (DateTime.Now >= entityCredentials.ExpirationTime.AddMinutes(-EXPIRATION_MINUTES)) { var accessToken = await RefreshAccessTokenAsync(entityCredentials.RefreshToken); return(accessToken); } else { return(entityCredentials.AccessToken); } }
private async Task <FacebookUser> GoogleDataAsync(GoogleCredentials credential) { var user = new FacebookUser(); user.name = credential.UserClaims.Where(x => x.Type == "name").FirstOrDefault().Value; user.email = credential.UserClaims.Where(x => x.Type == ClaimTypes.Email).FirstOrDefault().Value; user.id = credential.UserClaims.Where(x => x.Type == ClaimTypes.NameIdentifier).FirstOrDefault().Value; var urlPicture = credential.UserClaims.Where(x => x.Type == "picture").FirstOrDefault().Value; HttpClient client = new HttpClient(); user.profile_image = await client.GetByteArrayAsync(urlPicture); return(user); }
public YTClient(string appname, GoogleCredentials credentials, bool debug = false) { appName = appname; googleCredentials = credentials; loggers = new List <ILogger>(); youTubeAPI = new YouTubeAPI(); messageListeners = new List <ChatEventsListener>(); JoinedChannels = new List <JoinedChannel>(); Debug = debug; this.OnConnectEvent += YTClient_OnConnectEvent; this.OnDisconnectEvent += YTClient_OnDisconnectEvent; this.OnReceiveMessageEvent += YTClient_OnReceiveMessageEvent; }
/// <summary> /// GET api/UserProfile/UserName/<provider> /// </summary> /// <param name="provider">The MobileServiceAuthenticationProvider value that specifies which provider to access</param> /// <returns>Returns the user's display name</returns> /// <remarks> /// If you need other properties from the provider then add additional API to this controller /// </remarks> async public Task <string> GetUserName(string provider) { string userName = null; try { if (provider == "MicrosoftAccount") { MicrosoftAccountCredentials credential = await User.GetAppServiceIdentityAsync <MicrosoftAccountCredentials>(Request); userName = credential.Claims["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"]; } else if (provider == "Google") { GoogleCredentials credential = await User.GetAppServiceIdentityAsync <GoogleCredentials>(Request); userName = credential.Claims["name"]; } else if (provider == "Twitter") { TwitterCredentials credential = await User.GetAppServiceIdentityAsync <TwitterCredentials>(Request); userName = credential.Claims["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"]; } else if (provider == "Facebook") { FacebookCredentials credential = await User.GetAppServiceIdentityAsync <FacebookCredentials>(Request); userName = credential.Claims["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"]; } else if (provider == "WindowsAzureActiveDirectory") { AzureActiveDirectoryCredentials credential = await User.GetAppServiceIdentityAsync <AzureActiveDirectoryCredentials>(Request); userName = credential.Claims["name"]; } } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Exception in UserProfileController.GetUserName(): " + e.Message); userName = "******"; } return(userName); }
public void LogIn_Login_and_password_valid_doc_presented_User_is_logged_in() { //arrange GoogleCredentials target = CreateGoogleCredentials(); //act string userName = "******"; target.LogIn(userName, "MemorizeIt"); //assert Assert.That(target.IsLoggedIn, Is.EqualTo(true)); var user = target.GetCurrentUser(); Assert.That(user.Login, Is.EqualTo(userName)); }
public async Task <object> Get() { FacebookCredentials fbCreds = await this.User.GetAppServiceIdentityAsync <FacebookCredentials>(this.Request); TwitterCredentials twitterCreds = await this.User.GetAppServiceIdentityAsync <TwitterCredentials>(this.Request); GoogleCredentials googCreds = await this.User.GetAppServiceIdentityAsync <GoogleCredentials>(this.Request); MicrosoftAccountCredentials msCreds = await this.User.GetAppServiceIdentityAsync <MicrosoftAccountCredentials>(this.Request); AzureActiveDirectoryCredentials aadCreds = await this.User.GetAppServiceIdentityAsync <AzureActiveDirectoryCredentials>(this.Request); return(new { FacebookCreds = fbCreds, TwitterCreds = twitterCreds, GoogleCreds = googCreds, MicrosoftAccountCreds = msCreds, AadCreds = aadCreds, Claims = (this.User as ClaimsPrincipal).Claims.Select(c => new { Type = c.Type, Value = c.Value }) }); }
public DlgBrowse(Settings settingsToEdit, ITranslationProviderCredentialStore credentialStore, DialogMode mode) { _mode = mode; _credentialStore = credentialStore; _dataStore = new GoogleCredentialsDataStore(); _googleCredentials = _dataStore.Load(); _settingsToEdit = settingsToEdit; InitializeComponent(); SetIcons(); SetTitle(); _comboBoxGoogleUser.Text = string.Empty; txtApiKey.Text = string.Empty; btnOK.Enabled = false; UpdateAPIKeyFromCredentials(_settingsToEdit); UpdateTranslationModel(_settingsToEdit); btnRemove.Visible = false; }
public GoogleDirectionsRequest(GoogleCredentials credentials) : base(credentials) { }
protected GoogleApiRequest(GoogleCredentials credentials) { _credentials = credentials; }
public GoogleForwardGeocodingRequest(GoogleCredentials credentials) : base(credentials) { }
internal static void PopulateProviderCredentials(TokenEntry tokenEntry, ProviderCredentials credentials) { if (tokenEntry.UserClaims != null) { Collection <Claim> userClaims = new Collection <Claim>(); foreach (ClaimSlim claim in tokenEntry.UserClaims) { userClaims.Add(new Claim(claim.Type, claim.Value)); } credentials.UserClaims = userClaims; } FacebookCredentials facebookCredentials = credentials as FacebookCredentials; if (facebookCredentials != null) { facebookCredentials.AccessToken = tokenEntry.AccessToken; facebookCredentials.UserId = tokenEntry.UserId; return; } GoogleCredentials googleCredentials = credentials as GoogleCredentials; if (googleCredentials != null) { googleCredentials.AccessToken = tokenEntry.AccessToken; googleCredentials.RefreshToken = tokenEntry.RefreshToken; googleCredentials.UserId = tokenEntry.UserId; googleCredentials.AccessTokenExpiration = tokenEntry.ExpiresOn; return; } AzureActiveDirectoryCredentials aadCredentials = credentials as AzureActiveDirectoryCredentials; if (aadCredentials != null) { aadCredentials.AccessToken = tokenEntry.IdToken; Claim objectIdClaim = credentials.UserClaims.FirstOrDefault(c => string.Equals(c.Type, ObjectIdentifierClaimType, StringComparison.OrdinalIgnoreCase)); if (objectIdClaim != null) { aadCredentials.ObjectId = objectIdClaim.Value; } Claim tenantIdClaim = credentials.UserClaims.FirstOrDefault(c => string.Equals(c.Type, TenantIdClaimType, StringComparison.OrdinalIgnoreCase)); if (tenantIdClaim != null) { aadCredentials.TenantId = tenantIdClaim.Value; } aadCredentials.UserId = tokenEntry.UserId; return; } MicrosoftAccountCredentials microsoftAccountCredentials = credentials as MicrosoftAccountCredentials; if (microsoftAccountCredentials != null) { microsoftAccountCredentials.AccessToken = tokenEntry.AccessToken; microsoftAccountCredentials.RefreshToken = tokenEntry.RefreshToken; microsoftAccountCredentials.UserId = tokenEntry.UserId; microsoftAccountCredentials.AccessTokenExpiration = tokenEntry.ExpiresOn; return; } TwitterCredentials twitterCredentials = credentials as TwitterCredentials; if (twitterCredentials != null) { twitterCredentials.AccessToken = tokenEntry.AccessToken; twitterCredentials.AccessTokenSecret = tokenEntry.AccessTokenSecret; twitterCredentials.UserId = tokenEntry.UserId; return; } }
public GoogleOAuth(GoogleCredentials credentials) { this._credentials = credentials; }
internal static void PopulateProviderCredentials(TokenEntry tokenEntry, ProviderCredentials credentials) { if (tokenEntry.UserClaims != null) { credentials.Claims = new Dictionary <string, string>(); foreach (ClaimSlim claim in tokenEntry.UserClaims) { credentials.Claims[claim.Type] = claim.Value; } } FacebookCredentials facebookCredentials = credentials as FacebookCredentials; if (facebookCredentials != null) { facebookCredentials.AccessToken = tokenEntry.AccessToken; facebookCredentials.UserId = tokenEntry.UserId; return; } GoogleCredentials googleCredentials = credentials as GoogleCredentials; if (googleCredentials != null) { googleCredentials.AccessToken = tokenEntry.AccessToken; googleCredentials.RefreshToken = tokenEntry.RefreshToken; googleCredentials.UserId = tokenEntry.UserId; googleCredentials.AccessTokenExpiration = tokenEntry.ExpiresOn; return; } AzureActiveDirectoryCredentials aadCredentials = credentials as AzureActiveDirectoryCredentials; if (aadCredentials != null) { aadCredentials.AccessToken = tokenEntry.IdToken; aadCredentials.ObjectId = credentials.Claims.GetValueOrDefault(ObjectIdentifierClaimType); aadCredentials.TenantId = credentials.Claims.GetValueOrDefault(TenantIdClaimType); aadCredentials.UserId = tokenEntry.UserId; return; } MicrosoftAccountCredentials microsoftAccountCredentials = credentials as MicrosoftAccountCredentials; if (microsoftAccountCredentials != null) { microsoftAccountCredentials.AccessToken = tokenEntry.AccessToken; microsoftAccountCredentials.RefreshToken = tokenEntry.RefreshToken; microsoftAccountCredentials.UserId = tokenEntry.UserId; microsoftAccountCredentials.AccessTokenExpiration = tokenEntry.ExpiresOn; return; } TwitterCredentials twitterCredentials = credentials as TwitterCredentials; if (twitterCredentials != null) { twitterCredentials.AccessToken = tokenEntry.AccessToken; twitterCredentials.AccessTokenSecret = tokenEntry.AccessTokenSecret; twitterCredentials.UserId = tokenEntry.UserId; return; } }
public GoogleReverseGeocodingRequest(GoogleCredentials credentials) : base(credentials) { }
protected GoogleGeoLocationRequest(GoogleCredentials credentials) : base(credentials) { }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Configure the db context, user manager and signin manager to use a single instance per request app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create); app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create); // Enable the application to use a cookie to store information for the signed in user // and to use a cookie to temporarily store information about a user logging in with a third party login provider // Configure the sign in cookie app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider { // Enables the application to validate the security stamp when the user logs in. // This is a security feature which is used when you change a password or add an external login to your account. OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) } }); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process. app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5)); // Enables the application to remember the second login verification factor such as phone or email. // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from. // This is similar to the RememberMe option when you log in. app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie); // Uncomment the following lines to enable logging in with third party login providers //app.UseMicrosoftAccountAuthentication( // clientId: "", // clientSecret: ""); //app.UseTwitterAuthentication( // consumerKey: "", // consumerSecret: ""); //app.UseFacebookAuthentication( // appId: "", // appSecret: ""); string path = HostingEnvironment.MapPath("~/App_Data/auth.googlecreds"); if (File.Exists(path)) { string content = File.ReadAllText(path); GoogleCredentials gc = JsonConvert.DeserializeObject <GoogleCredentials>(content); app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() { ClientId = gc.ClientId, ClientSecret = gc.ClientSecret }); } }