// called by .auth command - build auth code & send to user
        public async Task GetAuthCode(SocketCommandContext context)
        {
            // build authentication url and send it to user
            using (var stream = new FileStream(_filePath, FileMode.Open, FileAccess.Read))
            {
                // build code flow manager to get auth url
                var flowManager = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = GoogleClientSecrets.Load(stream).Secrets,
                    Scopes        = _scopes,
                });

                // build auth url
                var request = flowManager.CreateAuthorizationCodeRequest(_redirectUri);
                var url     = request.Build();

                // put together a response message to give user instructions on what to do
                StringBuilder sb = new StringBuilder();
                sb.Append("Authorize your Google account using the following link. When you've finished following the instructions " +
                          "and you're given a connection error, copy the URL from your browser and paste it here.");
                sb.AppendLine();
                sb.AppendLine();
                sb.AppendLine($"{url.AbsoluteUri}");

                await _interactiveService.ReplyAndDeleteAsync(context, sb.ToString(), false, null,
                                                              TimeSpan.FromMinutes(1));
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Redirects the user to the OAuth server.
        /// </summary>
        public IActionResult RedirectUsertoOAuthServer()
        {
            Uri authorizationUrl = flow.CreateAuthorizationCodeRequest(
                GetCurrentPagePath()).Build();

            return(new RedirectResult(authorizationUrl.AbsoluteUri));
        }
Esempio n. 3
0
        public JsonResult SolicitudPermisoDriveDownload(List <dtoAsuntos> Archivos)
        {
            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        = Scopes,
            };
            var    googleCodeFlow = new GoogleAuthorizationCodeFlow(initializer);
            string redirectUrl    = $"https://{Request.Url.Host}:{Request.Url.Port}/{Url.Action(nameof(this.DownloadFileDrive)).TrimStart('/')}";
            var    codeRequestUrl = googleCodeFlow.CreateAuthorizationCodeRequest(redirectUrl);

            codeRequestUrl.ResponseType = "code";
            var authorizationUrl = codeRequestUrl.Build();
            var UserId           = User.Identity.GetUserId();

            Session["IdUsuario"]             = UserId;
            Session["ArchivosDownloadDrive"] = (List <dtoAsuntos>)Archivos;
            return(Json(new { Redireccion = authorizationUrl.AbsoluteUri }, JsonRequestBehavior.AllowGet));
        }
Esempio n. 4
0
        public IActionResult GoogleOAuth(string accountNumber, string userId)
        {
            _bankAccountService.SetAboutToConnectProperty(accountNumber, userId);
            string redirectUri = _oAuthConfig.Providers[0].RedirectUri;   /* _configuration["OAUTH:redirectUri"];*/

            string clientID = _oAuthConfig.Providers[0].ClientId;         /*_configuration["OAUTH:clientID"];*/

            string clientSecret = _oAuthConfig.Providers[0].ClientSecret; /*_configuration["OAUTH:clientSecret"];*/


            var clientSecrets = new ClientSecrets
            {
                ClientId     = clientID,
                ClientSecret = clientSecret
            };

            var credential = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = clientSecrets,
                Scopes        = new[] { GoogleScope.ImapAndSmtp.Name, GoogleScope.UserInfoEmailScope.Name }
            });

            AuthorizationCodeRequestUrl url = credential.CreateAuthorizationCodeRequest(redirectUri);

            return(new RedirectResult(url.Build().ToString()));
        }
Esempio n. 5
0
        public string SolicitudPermisoDrive()
        {
            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        = Scopes,
            };
            var    googleCodeFlow = new GoogleAuthorizationCodeFlow(initializer);
            string redirectUrl    = $"https://{Request.Url.Host}:{Request.Url.Port}/{Url.Action(nameof(this.GetAuthenticationTokenDrive)).TrimStart('/')}";
            var    codeRequestUrl = googleCodeFlow.CreateAuthorizationCodeRequest(redirectUrl);

            codeRequestUrl.ResponseType = "code";
            var authorizationUrl = codeRequestUrl.Build();
            var UserId           = User.Identity.GetUserId();

            Session["IdUsuario"] = UserId;
            return(authorizationUrl.AbsoluteUri);
        }
Esempio n. 6
0
        //solo para documentos
        public ActionResult RedirectCentral(int?id, int?tiendaId,
                                            string nombreDocumento, int?usuarioId)
        {
            if (Session["TiendaId"] == null)
            {
                return(RedirectToAction("IniciarSesion", "Login"));
            }

            tiendaId  = (int)Session["TiendaId"];
            usuarioId = (int)Session["Id"];

            try
            {
                CrearCredencialNormal();

                AuthorizationCodeRequestUrl url = credentialClienteNormal.CreateAuthorizationCodeRequest(redirectUri);
                url.State = tiendaId + "|" + id + "|" + nombreDocumento + "|" + usuarioId;

                return(new RedirectResult(url.Build().ToString()));
            }
            catch (Exception e)
            {
                TempData["msgEmail"] = "Aviso: Sistema de correo electrónico deshabilitado temporalmente.";

                //ReporteErrores.CrearReporteError(db,
                //"Catch antes de seleccionar email. Pista: " + pista + " MensajeException= " + e.Message + " ExeptionFULL= " + e.ToString());
                return(RedirectToAction("ResultadoMail", new { msgTest = "ad1" }));
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Redirects the user to the OAuth server.
        /// </summary>
        public void RedirectUsertoOAuthServer()
        {
            Uri authorizationUrl = flow.CreateAuthorizationCodeRequest(
                GetCurrentPagePath()).Build();

            page.Response.Redirect(authorizationUrl.AbsoluteUri);
        }
        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);
        }
Esempio n. 9
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());
        }
Esempio n. 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);
        }
Esempio n. 11
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);
        }
Esempio n. 12
0
        public ActionResult <string> GetAuthorizationCodeRequestUrl([Required] string scope)
        {
            if (string.IsNullOrEmpty(scope))
            {
                throw new ArgumentException("message", nameof(scope));
            }

            AuthorizationCodeRequestUrl authorizationCodeRequestUrl = flow.CreateAuthorizationCodeRequest(OAuthRedirectUri);

            authorizationCodeRequestUrl.Scope = scope;
            Uri authorizationUrl = authorizationCodeRequestUrl.Build();

            return(authorizationUrl.AbsoluteUri);
        }
Esempio n. 13
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);
        }
Esempio n. 14
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());
        }
Esempio n. 15
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);
        }
Esempio n. 16
0
        public async Task <string> GetGoogleLinkUrl(string userId, string redirectUri)
        {
            var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer()
            {
                ClientSecrets = new Google.Apis.Auth.OAuth2.ClientSecrets()
                {
                    ClientId     = options.GoogleClientID,
                    ClientSecret = options.GoogleClientSecret
                },
                Scopes = new[] { "https://www.googleapis.com/auth/calendar.events.readonly",
                                 "https://www.googleapis.com/auth/calendar.readonly" }
            });
            var request = flow.CreateAuthorizationCodeRequest(options.GoogleRedirectUri);
            var state   = Guid.NewGuid().ToString();

            request.State = state;
            await repository.CreateConfigState(userId, state, redirectUri);

            return(request.Build().AbsoluteUri);
        }
Esempio n. 17
0
        private async void GoogleAuth()
        {
            var currdir = "/opt/usr/apps/org.tizen.example.TizenXamlApp1.TV/res/";

            using (var stream = new FileStream(currdir + "client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(
                    new GoogleAuthorizationCodeFlow.Initializer()
                {
                    ClientSecretsStream = stream,
                    Scopes = new string[] { "https://www.googleapis.com/auth/photoslibrary" }
                }
                    );


                var request = flow.CreateAuthorizationCodeRequest("http://localhost").Build();
                var path    = request.AbsoluteUri;

                Page responcePage = new ResponcePage();

                await Navigation.PushModalAsync(responcePage);
            }
        }
Esempio n. 18
0
        public ActionResult <string> GetSignInGDUrl()
        {
            int accountId = JWTUtility.GetIdFromRequestHeaders(Request.Headers);

            if (accountId == -1)
            {
                return(BadRequest());
            }

            using var stream = new FileStream("googleDriveSecrets.json", FileMode.Open, FileAccess.Read);

            IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecretsStream = stream,
                Scopes    = _gdScopes,
                DataStore = _dataStore
            });

            var request = flow.CreateAuthorizationCodeRequest(_config.GetValue <string>("GDRedirectURL"));

            string url = request.Build().ToString();

            return(Ok(url));
        }