Ejemplo n.º 1
0
        private async Task RunUsingServiceAccount()
        {
            var requestUri = "path to server resource we want";

            IAuthorizationCodeFlow authFLow           = null;
            var           userId                      = "";
            TokenResponse token                       = null;
            var           authUri                     = "";
            ConfigurableMessageHandler messageHandler = new ConfigurableMessageHandler(
                new MyHandler()
                );

            var cancellationToken = new CancellationToken();

            cancellationToken.Register(() => { });

            var credential = new UserCredential(authFLow, userId, token)
            {
            };
            var accessToken = await credential.GetAccessTokenForRequestAsync(authUri, cancellationToken);

            // Create the service.
            var service = new Google.Apis.Datastore.v1beta3.DatastoreService(new BaseClientService.Initializer
            {
                ApplicationName = "Discovery Sample",
                ApiKey          = "[YOUR_API_KEY_HERE]",
            });

            var httpClient = new ConfigurableHttpClient(messageHandler);

            service.HttpClientInitializer.Initialize(httpClient);

            var res = await httpClient.GetAsync(requestUri);
        }
 /// <summary>
 /// Constructs a new authorization code installed application with the given flow and code receiver.
 /// </summary>
 public AuthorizationCodeWebApp(IAuthorizationCodeFlow flow, string redirectUri, string state)
 {
     // TODO(peleyal): Provide a way to disable to random number in the end of the state parameter.
     this.flow        = flow;
     this.redirectUri = redirectUri;
     this.state       = state;
 }
Ejemplo n.º 3
0
        public static UserCredential GetUserCredentialByRefreshToken(ApiDbContext _context, out string error)
        {
            UserCredential credential    = null;
            TokenResponse  responseToken = null;
            string         refreshToken  = string.Empty;
            string         flowError;

            error = string.Empty;

            try
            {
                IAuthorizationCodeFlow flow = GoogleAuthorizationCodeFlow(out flowError);

                var user = _context.Users.FirstOrDefault();
                refreshToken  = user.Refreshtoken;
                responseToken = new TokenResponse()
                {
                    RefreshToken = refreshToken
                };
                credential = new UserCredential(flow, "user", responseToken);
                if (credential != null)
                {
                    bool success = credential.RefreshTokenAsync(CancellationToken.None).Result;
                }
            }

            catch (Exception e)
            {
                credential = null;
                error      = "Fallo autorizacion : " + e.Message;
            }
            return(credential);
        }
 /// <summary>
 /// Constructs a new authorization code installed application with the given flow and code receiver.
 /// </summary>
 public AuthorizationCodeWebApp(IAuthorizationCodeFlow flow, string redirectUri, string state)
 {
     // TODO(peleyal): Provide a way to disable to random number in the end of the state parameter.
     this.flow = flow;
     this.redirectUri = redirectUri;
     this.state = state;
 }
Ejemplo n.º 5
0
 public Initializer(IAuthorizationCodeFlow authCodeFlow,
                    ApplicationCredentials secret,
                    IServiceConfigurationFactory configurationFactory)
 {
     Secret               = secret;
     AuthCodeFlow         = authCodeFlow;
     ConfigurationFactory = configurationFactory;
 }
Ejemplo n.º 6
0
 static MyMailFlowMetadata()
 {
     using (var sr = new FileStream(System.Web.Hosting.HostingEnvironment.MapPath("~/secrets.json"), FileMode.Open, FileAccess.Read))
       {
     flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer()
     {
       ClientSecrets = GoogleClientSecrets.Load(sr).Secrets,
       Scopes = new[] { GmailService.Scope.GmailReadonly },
       DataStore = new Google.Apis.Util.Store.FileDataStore("Gmail.Api.Auth.Store")
     });
       }
 }
Ejemplo n.º 7
0
 static AppFlowMetadata()
 {
     flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer()
     {
         ClientSecrets = new ClientSecrets
         {
             ClientId     = CLIENT_ID,
             ClientSecret = CLIENT_SECRET
         },
         Scopes = new[] { DriveService.Scope.Drive }
         //,DataStore = new FileDataStore("C:\\secure\\Drive.Api.Auth.Store", true)
     });
 }
Ejemplo n.º 8
0
 public static AuthorizationCodeWebApp.AuthResult GetAuthResult(String uri, String user_id)
 {
     try
     {
         IAuthorizationCodeFlow flow = GetAuthCodeFlow();
         if (flow != null)
         {
             return(new AuthorizationCodeWebApp(flow, uri, uri).AuthorizeAsync(user_id, CancellationToken.None).Result);
         }
     }
     catch (Exception r) { Util.Debug("Error getting AuthorizationCodeWebApp.AuthResult: " + Environment.NewLine + r.Message + " " + r.StackTrace); }
     return(null);
 }
    protected void Authenticate()
    {
        var code = Request["code"];

        if (String.IsNullOrEmpty(code))
        {
            // See if we're authed
            AuthorizationCodeWebApp.AuthResult AuthResult = LeadsUtil.GetAuthResult(hf_uri.Value, hf_user_id.Value);
            if (AuthResult != null)
            {
                // User is authenticated..
                if (AuthResult.RedirectUri == null)
                {
                    lbl_title.Text = "You are now authenticated with Google Mail API.. you can close this window and return to DataGeek.";
                }
                // User is not authenticated, start the authentication process..
                else
                {
                    // Redirect the user to the authorization server.
                    Response.Redirect(AuthResult.RedirectUri);
                }
            }
            else
            {
                Util.PageMessageAlertify(this, "Error getting auth result from Google, please try reloading this page.");
            }
        }
        else // When returning with a code to complete in-process authentication
        {
            IAuthorizationCodeFlow flow = LeadsUtil.GetAuthCodeFlow();
            if (flow != null)
            {
                var token = flow.ExchangeCodeForTokenAsync(hf_user_id.Value, code, hf_uri.Value.Substring(0, hf_uri.Value.IndexOf("?")), CancellationToken.None).Result;

                // Extract the right state.
                try
                {
                    var oauthState = AuthWebUtility.ExtracRedirectFromState(flow.DataStore, hf_user_id.Value, Request["state"]).Result;
                    Response.Redirect(oauthState);
                }
                catch
                {
                    Response.Redirect("authwithgmapi.aspx");
                }
            }
            else
            {
                Util.PageMessageAlertify(this, "Error getting token from Google, please try reloading this page.");
            }
        }
    }
Ejemplo n.º 10
0
        public AppFlowMetadata(Guid userId, IGoogleOAuthDataStore dataStore)
        {
            _userId = userId;

            _flow =
                new ForceOfflineGoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = new ClientSecrets {
                    ClientId = ConsumerKey, ClientSecret = ConsumerSecret
                },
                Scopes    = new[] { AnalyticsReportingService.Scope.AnalyticsReadonly },
                DataStore = dataStore
            });
        }
Ejemplo n.º 11
0
        static GoogleDriveHelper()
        {
            var flowInitializer = new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = new ClientSecrets
                {
                    ClientId = GoogleDriveClientId,
                    ClientSecret = GoogleDriveClientSecret
                },
                Scopes = Scopes,
                HttpClientFactory = new GoogleDriveHttpClientFactory()
            };

            AuthFlow = new GoogleAuthorizationCodeFlow(flowInitializer);
        }
Ejemplo n.º 12
0
        static GoogleDriveHelper()
        {
            var flowInitializer = new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = new ClientSecrets
                {
                    ClientId     = GoogleDriveClientId,
                    ClientSecret = GoogleDriveClientSecret
                },
                Scopes            = Scopes,
                HttpClientFactory = new GoogleDriveHttpClientFactory()
            };

            AuthFlow = new GoogleAuthorizationCodeFlow(flowInitializer);
        }
Ejemplo n.º 13
0
        //public AppFlowMetadata() { }

        public AppFlowMetadata(string appId, string appSecret)
        {
            AppId     = appId;
            AppSecret = appSecret;
            flow      =
                new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = new ClientSecrets
                {
                    ClientId     = AppId,
                    ClientSecret = AppSecret
                },
                Scopes    = new[] { "email" },
                DataStore = new FileDataStore("Drive.Api.Auth.Store")
            });
        }
Ejemplo n.º 14
0
        public static UserCredential GetGoogleUserCredentialByRefreshToken(string refreshToken)
        {
            UserCredential userCredential = null;

            IAuthorizationCodeFlow authorizationCodeFlow = GoogleAuthorizationCodeFlow();

            TokenResponse tokenResponse = new TokenResponse()
            {
                RefreshToken = refreshToken
            };

            if (authorizationCodeFlow != null && tokenResponse != null)
            {
                userCredential = new UserCredential(authorizationCodeFlow, "user", tokenResponse);
            }
            return(userCredential);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// function generates the google oauth credentials
        /// </summary>
        /// <returns></returns>
        public Google.Apis.Auth.OAuth2.UserCredential getGoogleOauthCredentials()
        {
            Google.Apis.Auth.OAuth2.Responses.TokenResponse responseData = new Google.Apis.Auth.OAuth2.Responses.TokenResponse();
            responseData.AccessToken  = this.Token;
            responseData.RefreshToken = this.RefreshToken;
            GoogleAuthorizationCodeFlow.Initializer myInit         = new GoogleAuthorizationCodeFlow.Initializer();
            AuthorizationCodeFlow.Initializer       codeFlowIntial = myInit;
            codeFlowIntial.ClientSecrets = new ClientSecrets();
            string googleClientId     = ConfigurationManager.AppSettings["googleClientId"];
            string googleClientSecret = ConfigurationManager.AppSettings["googleClientSecret"];

            codeFlowIntial.ClientSecrets.ClientId     = googleClientId;
            codeFlowIntial.ClientSecrets.ClientSecret = googleClientSecret;
            IAuthorizationCodeFlow myFlow = AppFlowMetadata.getFlow();

            Google.Apis.Auth.OAuth2.UserCredential RetValue = new Google.Apis.Auth.OAuth2.UserCredential(myFlow, this.ID, responseData);
            return(RetValue);
        }
Ejemplo n.º 16
0
        public static UserCredential GetGoogleUserCredentialByRefreshToken(string refreshToken, out string error)
        {
            TokenResponse  respnseToken = null;
            UserCredential credential   = null;
            string         flowError;

            error = string.Empty;
            try
            {
                // Get a new IAuthorizationCodeFlow instance
                IAuthorizationCodeFlow flow = GoogleAuthorizationCodeFlow(out flowError);


                respnseToken = new TokenResponse()
                {
                    RefreshToken = refreshToken
                };

                // Get a new Credential instance
                if ((flow != null && string.IsNullOrWhiteSpace(flowError)) && respnseToken != null)
                {
                    credential = new UserCredential(flow, "user", respnseToken);
                }

                // Get a new Token instance
                if (credential != null)
                {
                    bool success = credential.RefreshTokenAsync(CancellationToken.None).Result;
                }

                // Set the new Token instance
                if (credential.Token != null)
                {
                    string newRefreshToken = credential.Token.RefreshToken;
                }
            }
            catch (Exception ex)
            {
                credential = null;
                error      = "UserCredential failed: " + ex.ToString();
            }
            return(credential);
        }
Ejemplo n.º 17
0
        public static IAuthorizationCodeFlow GoogleAuthorizationCodeFlow(out string error)
        {
            IAuthorizationCodeFlow flow = null;

            error = string.Empty;
            try
            {
                flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = GoogleClienSecrets,
                    Scopes        = Scopes,
                });
            }
            catch (Exception e)
            {
                flow  = null;
                error = "Fallo el authorizationCodeFlow Initialization" + e.Message;
            }
            return(flow);
        }
Ejemplo n.º 18
0
        public static IAuthorizationCodeFlow GoogleAuthorizationCodeFlow(out string error)
        {
            IAuthorizationCodeFlow flow = null;

            error = string.Empty;

            try
            {
                flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = GoogleClientSecrets,
                    Scopes        = Scopes
                });
            }
            catch (Exception ex)
            {
                flow  = null;
                error = "Failed to AuthorizationCodeFlow Initialization: " + ex.ToString();
            }

            return(flow);
        }
Ejemplo n.º 19
0
 public BotUserCredential(IAuthorizationCodeFlow flow, User user, TokenResponse token) : base(flow, user.Id.ToString(), token)
 {
     From = user;
 }
 /// <summary>
 /// Constructs a new authorization code for Windows Phone targeting an installed application flow.
 /// </summary>
 /// <param name="flow">An authorization code flow.</param>
 public AuthorizationCodeWPInstalledApp(IAuthorizationCodeFlow flow)
 {
     innerInstallApp = new AuthorizationCodeInstalledApp(flow, new AuthorizationCodeBroker());
 }
 /// <summary>Constructs a new credential instance.</summary>
 /// <param name="flow">Authorization code flow.</param>
 /// <param name="userId">User identifier.</param>
 /// <param name="token">An initial token for the user.</param>
 public UserCredential(IAuthorizationCodeFlow flow, string userId, TokenResponse token)
 {
     this.flow = flow;
     this.userId = userId;
     this.token = token;
 }
 /// <summary>Constructs a new credential instance.</summary>
 /// <param name="flow">Authorization code flow.</param>
 /// <param name="userId">User identifier.</param>
 /// <param name="token">An initial token for the user.</param>
 public UserCredential(IAuthorizationCodeFlow flow, string userId, TokenResponse token)
 {
     this.flow   = flow;
     this.userId = userId;
     this.token  = token;
 }
Ejemplo n.º 23
0
 /// <inheritdoc />
 /// <summary>
 ///     This constructor provides a way to allow more control over the OAuth 2.0 authentication flow.
 /// </summary>
 /// <param name="flow">The OAuth authorization flow.</param>
 /// <param name="userId">The user ID string.</param>
 /// <param name="token">The OAuth token.</param>
 public PlatformRefreshTokenCredential(IAuthorizationCodeFlow flow, string userId, TokenResponse token)
     : base(flow, userId, token)
 {
 }
Ejemplo n.º 24
0
 public UserCredentials(Initializer initializer)
 {
     _flow     = initializer.AuthCodeFlow;
     _secret   = initializer.Secret;
     ApiConfig = initializer.ConfigurationFactory.CreateConfiguration();
 }
Ejemplo n.º 25
0
 public AccountController(BudgetContext budgetContext, Google.Apis.Auth.OAuth2.Flows.IAuthorizationCodeFlow authorizationFlow, IOptions <OAuthConfig> oauthConfig)
 {
     _budgetContext     = budgetContext;
     _authorizationFlow = authorizationFlow;
     _oauthConfig       = oauthConfig;
 }
Ejemplo n.º 26
0
        protected virtual void Dispose(bool disposing)
        {
            if (!disposing)
                return;

            if (_flow != null)
            {
                _flow.Dispose();
                _flow = null;
            }
        }
 /// <summary>
 /// Constructs a new authorization code installed application with the given flow and code receiver.
 /// </summary>
 public AuthorizationCodeInstalledApp(IAuthorizationCodeFlow flow, ICodeReceiver codeReceiver)
 {
     this.flow = flow;
     this.codeReceiver = codeReceiver;
 }
Ejemplo n.º 28
0
 /// <inheritdoc />
 /// <summary>
 /// </summary>
 /// <param name="flow">The OAuth authorization flow.</param>
 /// <param name="userId">The user ID string.</param>
 /// <param name="token">The OAuth token.</param>
 protected PlatformCredential(IAuthorizationCodeFlow flow, string userId, TokenResponse token)
     : base(flow, userId, token)
 {
 }
 /// <summary>
 /// Constructs a new authorization code installed application with the given flow and code receiver.
 /// </summary>
 public AuthorizationCodeInstalledApp(IAuthorizationCodeFlow flow, ICodeReceiver codeReceiver)
 {
     this.flow         = flow;
     this.codeReceiver = codeReceiver;
 }
 /// <summary>
 /// Constructs a new authorization code for Windows Store application targeting an installed application flow.
 /// </summary>
 /// <param name="flow">An authorization code flow.</param>
 public AuthorizationCodeWindowsInstalledApp(IAuthorizationCodeFlow flow)
 {
     innerInstallApp = new AuthorizationCodeInstalledApp(flow, new AuthorizationCodeBroker());
 }
Ejemplo n.º 31
-1
        public AppFlowMetadata(string applicationPath, string googleCredentialsJson)
        {
            try
            {
                GoogleClientJson googleClientJson = GoogleClientJson.Load(googleCredentialsJson);

                var initializer = new GoogleAuthorizationCodeFlow.Initializer
                                      {
                                          ClientSecrets = new ClientSecrets
                                                              {
                                                                  ClientId = googleClientJson.Web.ClientId,
                                                                  ClientSecret = googleClientJson.Web.ClientSecret
                                                              },
                                          Scopes = new[] {CalendarService.Scope.Calendar},
                                          DataStore = new FileDataStore(applicationPath, FileDataStoreFolder)
                                      };
                _flow = new GoogleAuthorizationCodeFlow(initializer);
                _googleUserId = googleClientJson.Web.ClientEmail;

                Valid = true;
            }
            catch (Exception e)
            {
                Logger.SetLog(e);
                Valid = false;
            }
        }