public void CreateAuthorizationCodeRequestTest()
        {
            var flow = new GoogleAuthorizationCodeFlow(initializer);

            var request = flow.CreateAuthorizationCodeRequest("TestRedirectUri") as GoogleAuthorizationCodeRequestUrl;

            Assert.Equal("offline", request.AccessType);
            Assert.Equal("true", request.IncludeGrantedScopes);
            Assert.Equal(userDefinedParams, request.UserDefinedQueryParams);
            Assert.Equal("TestRedirectUri", request.RedirectUri);
        }
Пример #2
0
        public void ConstructorTest()
        {
            var flow = new GoogleAuthorizationCodeFlow(initializer);

            Assert.Equal(initializer.RevokeTokenUrl, flow.RevokeTokenUrl);
            Assert.Equal(initializer.IncludeGrantedScopes, flow.IncludeGrantedScopes);
            Assert.Equal(initializer.LoginHint, flow.LoginHint);
            Assert.Equal(initializer.Prompt, flow.Prompt);
            Assert.Equal(initializer.Nonce, flow.Nonce);
            Assert.Equal(initializer.UserDefinedQueryParams, flow.UserDefinedQueryParams);
        }
Пример #3
0
        /// <summary>
        /// 저장위치와 접근 권한 설정을 해주는 함수
        /// </summary>
        /// <param name="initializer"> 초기 설정이 담겨있는 클래스</param>
        /// <param name="scopes"> 접근 권한이 담겨있음</param>
        /// <param name="user">사용자를 구별하기 위한 유저 이름 (닉네임)</param>
        /// <param name="taskCancellationToken"> 작업이 취소되지 않아야 함을 나타내는 값 : None으로 표시</param>
        /// <param name="dataStore"> 토큰값이 저장되는 경로 (설정 하지 않으면 null로 값이 들어감  (경로로 표시 : 기본 위치 -> C:\Users\bit-user\AppData\Roaming)) </param>
        /// <returns>반환값은 유저의 정보가 담긴 UserCredential 클래스 반환 </returns>
        private static async Task <UserCredential> AuthorizeAsyncCore(
            GoogleAuthorizationCodeFlow.Initializer initializer, IEnumerable <string> scopes, string user,
            CancellationToken taskCancellationToken, IDataStore dataStore = null)
        {
            initializer.Scopes    = scopes;
            initializer.DataStore = dataStore ?? new FileDataStore(Folder);
            GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(initializer);

            // 토큰을 이용하여 사용자의 정보를 얻어와서 반환해준다.
            return(await new googleauth(flow, new LocalServerCodeReceiver()).AuthorizeAsync
                       (user, taskCancellationToken).ConfigureAwait(false));
        }
Пример #4
0
        /// <summary>
        /// Starts the OAuth2.0 authorization process for web applications.
        /// Returns url to which client should be  redirected in order to give your app the access to Google Account.
        /// </summary>
        /// <param name="redirectUrl">postback url - google authorization will redirect back to this url</param>
        public virtual string AuthorizeWebAppBegin(string redirectUrl)
        {
            AuthorizationFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = ClientSecrets,
                Scopes        = Scopes
            });
            var request = AuthorizationFlow.CreateAuthorizationCodeRequest(redirectUrl);
            var uri     = request.Build();

            return(uri.ToString());
        }
Пример #5
0
        public ActionResult GetAuthenticationToken(string code)
        {
            if (String.IsNullOrEmpty(code))
            {
                return(View("Error"));
            }

            string        redirectUrl = $"https://{Request.Url.Host}:{Request.Url.Port}/{Url.Action(nameof(this.GetAuthenticationToken)).TrimStart('/')}";
            var           scopes      = new[] { "profile", "https://www.googleapis.com/auth/contacts.readonly" };
            string        path        = Server.MapPath("~/client_secrets.json");
            ClientSecrets Secrets     = null;

            using (var filestream = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                Secrets = GoogleClientSecrets.Load(filestream).Secrets;
            }
            var initializer = new GoogleAuthorizationCodeFlow.Initializer()
            {
                ClientSecrets = Secrets,
                Scopes        = new[] { "profile", "https://www.googleapis.com/auth/contacts.readonly" },
            };
            int UserIdPersona = 0;

            int.TryParse(Session["IdUsuario"].ToString(), out UserIdPersona);

            var googleCodeFlow = new GoogleAuthorizationCodeFlow(initializer);
            var token          = googleCodeFlow.ExchangeCodeForTokenAsync(UserIdPersona != 0 ? UserIdPersona.ToString() : Session["IdUsuario"].ToString(), code, redirectUrl, CancellationToken.None).Result;
            //var resultMVC = new AuthorizationCodeWebApp(googleCodeFlow, redirectUrl, redirectUrl).AuthorizeAsync(UserId.ToString(), CancellationToken.None).Result;
            UserCredential       credential = new UserCredential(googleCodeFlow, UserIdPersona != 0 ? UserIdPersona.ToString() : Session["IdUsuario"].ToString(), token);
            PeopleServiceService PeopleS    = new PeopleServiceService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName       = Application_Name,
                ApiKey = "AIzaSyBtEx9nIXbv-C-jEj45iIUZvs-HUP8SCc8"
            });
            var tokenJson = JsonConvert.SerializeObject(token);


            var RequestListado = PeopleS.People.Connections.List("people/me");

            RequestListado.PersonFields = "names,emailAddresses,phoneNumbers";
            var            response         = RequestListado.Execute();
            IList <Person> ListadoContactos = response.Connections;

            if (ListadoContactos != null)
            {
                ListadoContactos = ListadoContactos.Where(x => x.PhoneNumbers != null && x.EmailAddresses != null && x.Names != null).ToList();
            }
            Session["TokenPeople"]      = tokenJson;
            Session["ListadoContactos"] = ListadoContactos;

            return(RedirectToAction("Index", "Authorize"));
        }
        /// <summary>The core logic for asynchronously authorizing the specified user.</summary>
        /// <param name="initializer">The authorization code initializer.</param>
        /// <param name="scopes">
        /// The scopes which indicate the Google API access your application is requesting.
        /// </param>
        /// <param name="user">The user to authorize.</param>
        /// <param name="taskCancellationToken">Cancellation token to cancel an operation.</param>
        /// <param name="dataStore">The data store, if not specified a file data store will be used.</param>
        /// <returns>User credential.</returns>
        private static async Task <UserCredential> AuthorizeAsyncCore(AuthorizationCodeFlow.Initializer initializer,
                                                                      IEnumerable <string> scopes, string user, CancellationToken taskCancellationToken,
                                                                      IDataStore dataStore = null)
        {
            initializer.Scopes    = scopes;
            initializer.DataStore = dataStore ?? new FileDataStore(Folder);
            var flow = new GoogleAuthorizationCodeFlow(initializer);

            // Create authorization code installed app instance and authorize the user.
            return(await new AuthorizationCodeInstalledApp(flow, new LocalServerCodeReceiver()).AuthorizeAsync
                       (user, taskCancellationToken).ConfigureAwait(false));
        }
Пример #7
0
        public void WithHttpClientFactory()
        {
            var flow            = new GoogleAuthorizationCodeFlow(initializer);
            var factory         = new HttpClientFactory();
            var flowWithFactory = Assert.IsType <GoogleAuthorizationCodeFlow>(
                ((IHttpAuthorizationFlow)flow).WithHttpClientFactory(factory));

            Assert.NotSame(flow, flowWithFactory);
            Assert.NotSame(flow.HttpClient, flowWithFactory.HttpClient);
            Assert.NotSame(flow.HttpClientFactory, flowWithFactory.HttpClientFactory);
            Assert.Same(factory, flowWithFactory.HttpClientFactory);
        }
        public override async Task <AuthorizationFlowCredential> OnGetToken(string code, string redirectUri, string state)
        {
            var googleOptions = AuthenticationOptions.Get(this.SchemeName);

            try
            {
                var requestId             = $"GoogleAuthorizationFlow-{Guid.NewGuid()}";
                var authorizationCodeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer()
                {
                    ClientSecrets = new ClientSecrets()
                    {
                        ClientId     = googleOptions.ClientId,
                        ClientSecret = googleOptions.ClientSecret,
                    },
                    IncludeGrantedScopes = true,
                });
                var tokenResponse = await authorizationCodeFlow.ExchangeCodeForTokenAsync(
                    requestId,
                    code,
                    redirectUri,
                    CancellationToken.None);

                var payload = await GoogleJsonWebSignature.ValidateAsync(tokenResponse.IdToken);

                return(new AuthorizationFlowCredential
                {
                    UserId = payload.Subject,
                    Email = payload.Email,
                    DisplayName = payload.Name,
                    GivenName = payload.GivenName,
                    FamilyName = payload.FamilyName,
                    TokenType = tokenResponse.TokenType,
                    IdToken = tokenResponse.IdToken,
                    AccessToken = tokenResponse.AccessToken,
                    RefreshToken = tokenResponse.RefreshToken,
                    IssuedUtc = tokenResponse.IssuedUtc,
                    ExpiresInSeconds = tokenResponse.ExpiresInSeconds,
                    Scope = tokenResponse.Scope,
                });
            }
            catch (TokenResponseException ex)
            {
                Logger.LogError(ex, ex.Message);
                throw new AuthorizationFlowException(ex.Error.Error, ex.Error.ErrorDescription, ex.Error.ErrorUri);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, ex.Message);
                throw;
            }
        }
Пример #9
0
        public string SolicitudPermiso(DTOWDXDespachoVilla.Personas.dtoPersonas Persona, string Mensaje, bool AceptarOfertas, bool InvitarUsuarios)
        {
            bool _result = false;

            if (AceptarOfertas)
            {
                List <DTOWDXDespachoVilla.Personas.dtoPersonas> Listado = new List <DTOWDXDespachoVilla.Personas.dtoPersonas>
                {
                    Persona
                };
                _result = new BALWDXDespachoVilla.Personas.BALPersonas().UpdatePersona(Listado).Item1;
            }
            EmailService Servicio = new EmailService();

            Servicio.sendMailMensaje(Mensaje, Persona);
            if (InvitarUsuarios)
            {
                string        path    = Server.MapPath("~/client_secrets.json");
                ClientSecrets Secrets = null;
                using (var filestream = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    Secrets = GoogleClientSecrets.Load(filestream).Secrets;
                }
                var initializer = new GoogleAuthorizationCodeFlow.Initializer()
                {
                    ClientSecrets = Secrets,
                    Scopes        = new[] { "profile", "https://www.googleapis.com/auth/contacts.readonly" },
                };
                var    googleCodeFlow = new GoogleAuthorizationCodeFlow(initializer);
                string redirectUrl    = $"https://{Request.Url.Host}:{Request.Url.Port}/{Url.Action(nameof(this.GetAuthenticationToken)).TrimStart('/')}";
                var    codeRequestUrl = googleCodeFlow.CreateAuthorizationCodeRequest(redirectUrl);
                codeRequestUrl.ResponseType = "code";
                var authorizationUrl = codeRequestUrl.Build();
                var UserId           = (object)Guid.NewGuid();
                if (_result != false)
                {
                    UserId = new BALWDXDespachoVilla.Personas.BALPersonas().GetPersonasDirectorio(new List <DTOWDXDespachoVilla.Personas.dtoPersonas>()
                    {
                        Persona
                    }).FirstOrDefault(k => k.Telefono == Persona.Telefono).IdPersona;
                }
                Session["IdUsuario"] = UserId;
                return(authorizationUrl.AbsoluteUri);
            }
            else if ((AceptarOfertas && !_result))
            {
                return(DTOWDXDespachoVilla.Constantes.ConstantesComunes.ERROR_GENERICO);
            }
            return(DTOWDXDespachoVilla.Constantes.ConstantesComunes.CONTACTO_EXITO);
        }
Пример #10
0
        public void CreateAuthorizationCodeRequestTest()
        {
            var flow = new GoogleAuthorizationCodeFlow(initializer);

            var request = flow.CreateAuthorizationCodeRequest("TestRedirectUri") as GoogleAuthorizationCodeRequestUrl;

            Assert.Equal("offline", request.AccessType);
            Assert.Equal("true", request.IncludeGrantedScopes);
            Assert.Equal("*****@*****.**", request.LoginHint);
            Assert.Equal("select_account", request.Prompt);
            Assert.Equal("nonce", request.Nonce);
            Assert.Equal(userDefinedParams, request.UserDefinedQueryParams);
            Assert.Equal("TestRedirectUri", request.RedirectUri);
        }
Пример #11
0
        public ActionResult SendInvite([FromBody] GoogleInvite param)
        {
            var Token = GetAuthenticator();
            var token = new TokenResponse()
            {
                AccessToken      = Token,
                ExpiresInSeconds = 3600,
                IssuedUtc        = DateTime.UtcNow
            };

            var authflow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = new ClientSecrets
                {
                    ClientId     = ClientId,
                    ClientSecret = ClientSecret
                }
            });

            var credential         = new UserCredential(authflow, "0", token);
            var serviceInitializer = new BaseClientService.Initializer()
            {
                ApplicationName       = GoogleApplicationName,
                HttpClientInitializer = credential
            };

            var googleClassService = new ClassroomService(serviceInitializer);

            // string pageToken = null;

            foreach (var student in param.StudentList)
            {
                Invitation invitation = new Invitation();
                invitation.CourseId = param.CourseId;
                invitation.Role     = "STUDENT";
                invitation.UserId   = student.EmailID;
                var request = googleClassService.Invitations.Create(invitation);
                try
                {
                    var response = request.Execute();
                }
                catch (Exception ex)
                {
                    //TODO- Return the student List who are not invited
                }
            }

            return(Json(""));
        }
Пример #12
0
        private DriveService CreateDriveService()
        {
            DriveService service = null;
            string       UserId  = "user-id";
            GoogleAuthorizationCodeFlow flow;

            using (var stream = new FileStream(Server.MapPath(@"/client_secrets.json"), FileMode.Open, FileAccess.Read))
            {
                flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    DataStore           = new FileDataStore(Server.MapPath(@"/Drive.Sample.Store")),
                    ClientSecretsStream = stream,
                    Scopes = new[] { DriveService.Scope.Drive }
                });
            }
            var uri  = Request.Url.ToString();
            var code = Request["code"];

            if (code != null)
            {
                var token = flow.ExchangeCodeForTokenAsync(UserId, code,
                                                           uri.Substring(0, uri.IndexOf("?")), CancellationToken.None).Result;

                // Extract the right state.
                var oauthState = AuthWebUtility.ExtracRedirectFromState(
                    flow.DataStore, UserId, Request["state"]).Result;
                Response.Redirect(oauthState);
            }
            else
            {
                var result = new AuthorizationCodeWebApp(flow, uri, uri).AuthorizeAsync(UserId,
                                                                                        CancellationToken.None).Result;
                if (result.RedirectUri != null)
                {
                    // Redirect the user to the authorization server.
                    Response.Redirect(result.RedirectUri);
                }
                else
                {
                    // The data store contains the user credential, so the user has been already authenticated.
                    service = new DriveService(new BaseClientService.Initializer
                    {
                        ApplicationName       = "Google Drive API",
                        HttpClientInitializer = result.Credential
                    });
                }
            }
            return(service);
        }
Пример #13
0
        public static CalendarService GetCalendarService(GoogleTokenModel GoogleTokenModelObj)
        {
            CalendarService service = null;

            IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(
                new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = GetClientConfiguration().Secrets,
                DataStore     = new FileDataStore(gFolder),
                Scopes        = new[] { CalendarService.Scope.Calendar }
            });

            var uri  = /*"http://localhost:19594/GoogleCalendarRegistration.aspx";*/ System.Web.HttpContext.Current.Request.Url.ToString();
            var code = System.Web.HttpContext.Current.Request["code"];

            if (code != null)
            {
                var token = flow.ExchangeCodeForTokenAsync(UserId, code,
                                                           uri.Substring(0, uri.IndexOf("?")), CancellationToken.None).Result;

                // Extract the right state.
                var oauthState = AuthWebUtility.ExtracRedirectFromState(
                    flow.DataStore, UserId, HttpContext.Current.Request["state"]).Result;
                System.Web.HttpContext.Current.Response.Redirect(oauthState);
            }
            else
            {
                var result = new AuthorizationCodeWebApp(flow, uri, uri).AuthorizeAsync(UserId, CancellationToken.None).Result;
                if (result.RedirectUri != null)
                {
                    // Redirect the user to the authorization server.
                    System.Web.HttpContext.Current.Response.Redirect(result.RedirectUri);
                    //var page = System.Web.HttpContext.Current.CurrentHandler as Page;
                    //page.ClientScript.RegisterClientScriptBlock(page.GetType(),
                    //    "RedirectToGoogleScript", "window.top.location = '" + result.RedirectUri + "'", true);
                }
                else
                {
                    // The data store contains the user credential, so the user has been already authenticated.
                    service = new CalendarService(new BaseClientService.Initializer
                    {
                        ApplicationName       = "My ASP.NET Google Calendar App",
                        HttpClientInitializer = result.Credential
                    });
                }
            }

            return(service);
        }
Пример #14
0
    // This is a method we'll use to obtain the authorization code flow
    private AuthorizationCodeFlow GetGoogleAuthorizationCodeFlow(params string[] scopes)
    {
        var clientIdPath = @"C:\Path\To\My\client_id.json";

        using (var fileStream = new FileStream(clientIdPath, FileMode.Open, FileAccess.Read))
        {
            var clientSecrets = GoogleClientSecrets.Load(stream).Secrets;
            var initializer   = new GoogleAuthorizationCodeFlow.Initializer {
                ClientSecrets = clientSecrets, Scopes = scopes
            };
            var googleAuthorizationCodeFlow = new GoogleAuthorizationCodeFlow(initializer);

            return(googleAuthorizationCodeFlow);
        }
    }
Пример #15
0
        public TokenResponse GetToken(string authCode)
        {
            var flowManager = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = Secrets,
                Scopes        = Scopes
            });

            var token = flowManager.ExchangeCodeForTokenAsync("", authCode, "postmessage", CancellationToken.None).Result;

            Console.WriteLine("Access Token: {0}", token.AccessToken);
            Console.WriteLine("Refresh Token: {0}", token.RefreshToken);

            return(token);
        }
        public GoogleAppFlowMetaData(IDataStore dataStore, string clientID, string clientSecret)
        {
            var flowInitializer = new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = new ClientSecrets
                {
                    ClientId     = clientID,
                    ClientSecret = clientSecret
                },
                //Scopes = new[] { CalendarService.Scope.Calendar },
                DataStore = dataStore
            };

            flow = new GoogleAuthorizationCodeFlow(flowInitializer);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            GoogleAuthorizationCodeFlow flow;
            var assembly = Assembly.GetExecutingAssembly();

            using (var stream = assembly.GetManifestResourceStream("Tasks.ASP.NET.SimpleOAuth2.client_secrets.json"))
            {
                flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    DataStore           = new FileDataStore("Tasks.ASP.NET.Sample.Store"),
                    ClientSecretsStream = stream,
                    Scopes = new[] { TasksService.Scope.TasksReadonly }
                });
            }

            var uri  = Request.Url.ToString();
            var code = Request["code"];

            if (code != null)
            {
                var token = flow.ExchangeCodeForTokenAsync(UserId, code,
                                                           uri.Substring(0, uri.IndexOf("?")), CancellationToken.None).Result;

                // Extract the right state.
                var oauthState = AuthWebUtility.ExtracRedirectFromState(
                    flow.DataStore, UserId, Request["state"]).Result;
                Response.Redirect(oauthState);
            }
            else
            {
                var result = new AuthorizationCodeWebApp(flow, uri, uri).AuthorizeAsync(UserId,
                                                                                        CancellationToken.None).Result;
                if (result.RedirectUri != null)
                {
                    // Redirect the user to the authorization server.
                    Response.Redirect(result.RedirectUri);
                }
                else
                {
                    // The data store contains the user credential, so the user has been already authenticated.
                    service = new TasksService(new BaseClientService.Initializer
                    {
                        ApplicationName       = "Tasks API Sample",
                        HttpClientInitializer = result.Credential
                    });
                }
            }
        }
Пример #18
0
        public async Task RevokeFakeToken_BadRequest()
        {
            // Tests that the correct 400 response is received from the server, given an invalid token.
            // Validates the revoke URL and verb are correct.
            using (var f = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecretsStream = Helper.GetClientSecretStream()
            }))
            {
                var ex = await Assert.ThrowsAsync <TokenResponseException>(
                    () => f.RevokeTokenAsync("fake-user", "fake-token", default));

                Assert.Equal(HttpStatusCode.BadRequest, ex.StatusCode);
                Assert.Equal("invalid_token", ex.Error.Error);
            }
        }
Пример #19
0
        private GoogleAuthorizationCodeFlow GetGoogleAuthFlow()
        {
            var clientSecrets = new ClientSecrets()
            {
                ClientId     = _planerConfig.GetGoogleClientId(),
                ClientSecret = _planerConfig.GetGoogleClientSecret()
            };
            var googleFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = clientSecrets,
                Scopes        = new[] { CalendarService.Scope.Calendar },
                DataStore     = _dataStore
            });

            return(googleFlow);
        }
        /// Request Oauth2 credentials through Google.
        public OAuth2CredentialRequest(ClientSecrets secrets, IEnumerable <string> scopes,
                                       string callbackPath, IDataStore dataStore)
        {
            // Use Google authorization code flow, which has hardcoded authorization server and token server
            // URLs.
            IsGoogle = true;
            var initializer = new GoogleAuthorizationCodeFlow.Initializer {
                ClientSecrets = secrets,
                Scopes        = scopes,
                DataStore     = dataStore,
            };
            var authFlow     = new GoogleAuthorizationCodeFlow(initializer);
            var codeReceiver = new LocalHttpCodeReceiver(callbackPath);

            m_AppFlow = new AuthorizationCodeInstalledApp(authFlow, codeReceiver);
        }
Пример #21
0
        public async Task SaveTokenAsync(string token, long userId, string uri,
                                         CancellationToken cancellationToken)
        {
            using var child = _container.BeginLifetimeScope();
            var initializer = new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = GetGoogleClientSecrets().Secrets,
                Scopes        = new[] { CalendarService.Scope.CalendarReadonly },
                DataStore     = child.Resolve <GoogleDataStore>()
            };

            using var flow = new GoogleAuthorizationCodeFlow(initializer);
            await flow.ExchangeCodeForTokenAsync(userId.ToString(), token,
                                                 uri, // need to be in from google console
                                                 cancellationToken);
        }
Пример #22
0
        public string GetAuthorizationUrl()
        {
            var credential = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = new ClientSecrets
                {
                    ClientId     = ClientId,
                    ClientSecret = ClientSecret,
                },
                Scopes = new[] { Google.Apis.Gmail.v1.GmailService.Scope.GmailModify }
            });

            var url = credential.CreateAuthorizationCodeRequest(RedirectUri);

            return(url.Build().ToString());
        }
Пример #23
0
        public string AuthRequestUrl(string hostUrl)
        {
            var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = new ClientSecrets
                {
                    ClientId     = _googleDriveClientId,
                    ClientSecret = _googleDriveSecretId
                },
                Scopes = _googelDriveScopes,
            });

            var url = flow.CreateAuthorizationCodeRequest("https://" + hostUrl + "/Platform/ReturnGoogleAuth").Build();

            return(url.OriginalString);
        }
Пример #24
0
        async Task get_google_credential()
        {
            using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecretsStream = stream,
                    Scopes    = new[] { DriveService.Scope.DriveReadonly },
                    DataStore = new FileDataStore("oauth/drive")
                });

                TokenResponse token = await flow.LoadTokenAsync(Environment.UserName, CancellationToken.None);

                if (token == null)
                {
                    return;
                }

                credential = new UserCredential(flow, Environment.UserName, token);

                //bool res = await credential.RevokeTokenAsync(CancellationToken.None);
            }

            // Create Drive API service.
            driveService = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = this.GetType().ToString(),
            });

            var req = driveService.About.Get();

            req.Fields = "user(displayName,photoLink, me, emailAddress), storageQuota(limit,usage), maxImportSizes, maxUploadSize";
            try
            {
                About ab = await req.ExecuteAsync();

                lbUserinfo.Text      = $"{ab.User.DisplayName} - {ab.User.EmailAddress}";
                lbStorageamount.Text = $"{ab.StorageQuota.Usage.ToReadableSize()}/{ab.StorageQuota.Limit.ToReadableSize()}";
            }
            catch (TokenResponseException ex)
            {
                credential   = null;
                driveService = null;
                btnClearLocal.PerformClick();
            }
        }
Пример #25
0
        public async Task GetAndValidateJwt()
        {
            // Warning: This test is interactive!
            // It will bring up a browser window that must be responded to before the test can complete.

            // Do auth.
            var codeReceiver = new LocalServerCodeReceiver();
            var nonce        = "nonce_but_randomly_generate_in_real_code";
            var initializer  = new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecretsStream = Helper.GetClientSecretStream(),
                Scopes = new string[] { "openid", "email" },
                Nonce  = nonce,
            };
            var flow        = new GoogleAuthorizationCodeFlow(initializer);
            var redirectUri = codeReceiver.RedirectUri;
            AuthorizationCodeRequestUrl codeRequest = flow.CreateAuthorizationCodeRequest(redirectUri);

            // Receive the code.
            var response = await codeReceiver.ReceiveCodeAsync(codeRequest, CancellationToken.None);

            var code = response.Code;

            // Get a JWT from code.
            var secretJson = JToken.Parse(Helper.GetClientSecret());
            var codeReq    = "https://oauth2.googleapis.com/token";
            var contentStr = "code=" + code +
                             "&client_id=" + secretJson["installed"]["client_id"] +
                             "&client_secret=" + secretJson["installed"]["client_secret"] +
                             "&redirect_uri=" + redirectUri +
                             "&grant_type=authorization_code";
            var contentBytes = Encoding.ASCII.GetBytes(contentStr);
            var content      = new ByteArrayContent(contentBytes);

            content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
            var httpClient = new HttpClient();
            var res        = httpClient.PostAsync(codeReq, content).Result;
            var json       = JToken.Parse(Encoding.UTF8.GetString(await res.Content.ReadAsByteArrayAsync()));
            var jwt        = (string)json["id_token"];

            // Confirm JWT is valid
            var validPayload = await GoogleJsonWebSignature.ValidateAsync(jwt);

            Assert.NotNull(validPayload);
            // Confirm nonce matches
            Assert.Equal(nonce, validPayload.Nonce);
        }
Пример #26
0
        async void performCodeExchangeAsync(string code, string code_verifier)
        {
            // Builds the Token request
            string tokenRequestBody = string.Format("code={0}&redirect_uri={1}&client_id={2}&code_verifier={3}&scope=&grant_type=authorization_code",
                                                    code,
                                                    System.Uri.EscapeDataString(redirectURI),
                                                    clientID,
                                                    code_verifier
                                                    );
            StringContent content = new StringContent(tokenRequestBody, Encoding.UTF8, "application/x-www-form-urlencoded");

            // Performs the authorization code exchange.
            HttpClientHandler handler = new HttpClientHandler();

            handler.AllowAutoRedirect = true;
            HttpClient client = new HttpClient(handler);

            HttpResponseMessage response = await client.PostAsync(tokenEndpoint, content);

            string responseString = await response.Content.ReadAsStringAsync();

            if (!response.IsSuccessStatusCode)
            {
                // Log some kind of error or something
                return;
            }

            // Sets the Authentication header of our HTTP client using the acquired access token.
            JsonObject tokens       = JsonObject.Parse(responseString);
            string     refreshToken = tokens.GetNamedString("refresh_token");

            var token = new TokenResponse {
                RefreshToken = refreshToken
            };
            var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer());
            //{
            //    ClientSecrets = Secrets
            //});
            var credentials = new UserCredential(flow, "user", token);
            var initializer = new BaseClientService.Initializer()
            {
                HttpClientInitializer = credentials,
                ApplicationName       = "HulloVoicemail"
            };

            _service = new GmailService(initializer);
        }
Пример #27
0
        public GoogleAuthAdapter(
            GoogleAuthorizationCodeFlow.Initializer initializer,
            string closePageReponse)
        {
            // Add email scope.
            this.initializer = new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = initializer.ClientSecrets,
                Scopes        = initializer.Scopes.Concat(new[] { GoogleAuthAdapter.EmailScope }),
                DataStore     = initializer.DataStore
            };

            this.flow         = new GoogleAuthorizationCodeFlow(this.initializer);
            this.installedApp = new AuthorizationCodeInstalledApp(
                this.flow,
                new LocalServerCodeReceiver(closePageReponse));
        }
        public async void BatchDeleteFromTemplateEvents(int UserId, List <ExternalEventIds> externalEventIds)
        {
            string AccessToken = oAuthService.GetGoogleAccessToken(UserId);

            if (AccessToken != null && externalEventIds.Count != 0)
            {
                string[] scopes = new string[] { "https://www.googleapis.com/auth/calendar" };
                var      flow   = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = new ClientSecrets
                    {
                        ClientId     = oAuthService.GoogleClientId,
                        ClientSecret = oAuthService.GoogleClientSecret
                    },
                    Scopes    = scopes,
                    DataStore = new FileDataStore("Store")
                });
                var token = new TokenResponse
                {
                    AccessToken  = AccessToken,
                    RefreshToken = oAuthService.GetGoogleRefreshToken(UserId)
                };
                var credential = new UserCredential(flow, UserId.ToString(), token);

                var service = new CalendarService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName       = oAuthService.GoogleApplicationName,
                });

                var request = new BatchRequest(service);

                foreach (ExternalEventIds template in externalEventIds)
                {
                    if (template.GoogleId != null)
                    {
                        request.Queue <Event>(service.Events.Delete("primary", template.GoogleId),
                                              (content, error, i, message) =>
                        {
                            exCalHelperService.DeleteExternalEvent(template.GoogleId);
                        });
                    }
                }
                await request.ExecuteAsync();
            }
        }
Пример #29
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var serviceAccountEmail = "*****@*****.**";
                var certificate         = new X509Certificate2(@"D:\users\chris\testcert.cer", "notasecret", X509KeyStorageFlags.Exportable);


                IAuthorizationCodeFlow flow =
                    new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = GetClientConfiguration().Secrets,
                    Scopes        = new string[] { DriveService.Scope.DriveFile }
                });


                //TokenResponse response = flow.ExchangeCodeForTokenAsync("", code, "postmessage", CancellationToken.None).Result; // response.accessToken now should be populated



                UserCredential           credential1 = new UserCredential(null, "*****@*****.**", null);
                ServiceAccountCredential credential  = new ServiceAccountCredential(
                    new ServiceAccountCredential.Initializer(serviceAccountEmail)
                {
                    Scopes = new[] { DriveService.Scope.DriveReadonly }
                }.FromCertificate(certificate));

                // Create the service.

                var service = new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential1,
                    ApplicationName       = "Drive API Sample",
                });

                FilesResource.ListRequest request = service.Files.List();
                FileList files = request.Execute();
                string   s     = "";
                foreach (Google.Apis.Drive.v2.Data.File item in files.Items)
                {
                    s = item.Title;
                    s = s;
                }
            }
        }
 private UserCredential GetCredentials(string userEmailAddress)
 {
     if (_credentials == null)
     {
         var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer {
             ClientSecrets = GetClientSerects(),
             Scopes        = _scopes
         });
         var token = flow.LoadTokenAsync(userEmailAddress, CancellationToken.None).Result;
         _credentials = GoogleWebAuthorizationBroker.AuthorizeAsync(
             GetClientSerects(),
             _scopes,
             userEmailAddress,
             CancellationToken.None,
             new FileDataStore("Daimto.GoogleCalendar.Auth.Store")).Result;
     }
     return(_credentials);
 }