示例#1
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GoogleClientSecrets clientSecret;

                using (var stream = new FileStream(Gfolder + @"\client_secret.json", FileMode.Open, FileAccess.Read))
                {
                    clientSecret = GoogleClientSecrets.Load(stream);
                }

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

                var uri  = HttpContext.Current.Request.Url.ToString();
                var code = HttpContext.Current.Request["code"];
                if (code != null)
                {
                    var token = flow.ExchangeCodeForTokenAsync(UserId, code,
                                                               uri.Substring(0, uri.IndexOf("?")), CancellationToken.None).Result;

                    //儲存使用者的Token
                    var oauthState = AuthWebUtility.ExtracRedirectFromState(
                        flow.DataStore, UserId, Request["state"]).Result;

                    //印出儲存狀態
                    Response.Write(oauthState);
                }
            }
        }
        public async virtual Task <ActionResult> IndexAsync(AuthorizationCodeResponseUrl authorizationCode,
                                                            CancellationToken taskCancellationToken)
        {
            if (string.IsNullOrEmpty(authorizationCode.Code))
            {
                var errorResponse = new TokenErrorResponse(authorizationCode);
                Logger.Info("Received an error. The response is: {0}", errorResponse);

                return(OnTokenError(errorResponse));
            }

            Logger.Debug("Received \"{0}\" code", authorizationCode.Code);

            var returnUrl = Request.Url.ToString();

            returnUrl = returnUrl.Substring(0, returnUrl.IndexOf("?"));

            var token = await Flow.ExchangeCodeForTokenAsync(UserId, authorizationCode.Code, returnUrl,
                                                             taskCancellationToken).ConfigureAwait(false);

            // Extract the right state.
            var oauthState = await AuthWebUtility.ExtracRedirectFromState(Flow.DataStore, UserId,
                                                                          authorizationCode.State).ConfigureAwait(false);

            return(new RedirectResult(oauthState));
        }
示例#3
0
        public override async Task <ActionResult> IndexAsync(AuthorizationCodeResponseUrl authorizationCode,
                                                             CancellationToken taskCancellationToken)
        {
            if (string.IsNullOrEmpty(authorizationCode.Code))
            {
                var errorResponse = new TokenErrorResponse(authorizationCode);
                Logger.Info("Received an error. The response is: {0}", errorResponse);

                return(OnTokenError(errorResponse));
            }

            Logger.Debug("Received \"{0}\" code", authorizationCode.Code);

            var returnUrl = Request.Url.ToString();

            returnUrl = returnUrl.Substring(0, returnUrl.IndexOf("?"));

            //AS- make sure _ISessionInfo is initialized
            var l = _sessionInfo.CurrentAgencyId.GetValueOrDefault();
            var u = _setupBusiness.GetClientEmail(l);
            //AS

            var token = await Flow.ExchangeCodeForTokenAsync(u, authorizationCode.Code, returnUrl,
                                                             taskCancellationToken).ConfigureAwait(true);//AS-include context

            // Extract the right state.
            var oauthState = await AuthWebUtility.ExtracRedirectFromState(Flow.DataStore, u,
                                                                          authorizationCode.State).ConfigureAwait(true);//AS-include context

            return(new RedirectResult(oauthState));
        }
示例#4
0
        //
        //  Inherit methods from parent class

        override public object Authorize(HttpRequest Request, string accountName)
        {
            try
            {
                var uri   = Request.Url.ToString();
                var code  = Request["code"];
                var error = Request["error"];

                if (!string.IsNullOrEmpty(error))
                {
                    if (error == "access_denied")
                    {
                        return(new UserRejectException());
                    }
                    else
                    {
                        return(new UnknownException(error));
                    }
                }

                // перед авторизацией нужно обнулить
                CalendarService = null;

                if (code != null)
                {
                    string redirectUri = uri.Substring(0, uri.IndexOf("?"));
                    var    token       = CodeFlow.ExchangeCodeForTokenAsync(accountName, code, redirectUri, CancellationToken.None).Result;
                    string state       = Request["state"];
                    var    result      = AuthWebUtility.ExtracRedirectFromState(CodeFlow.DataStore, accountName, state);
                    return(result);
                }
                else
                {
                    string redirectUri = uri;
                    string state       = "ostate_";// Guid.NewGuid().ToString("N");
                    var    result      = new AuthorizationCodeWebApp(CodeFlow, redirectUri, state).AuthorizeAsync(accountName, CancellationToken.None).Result;
                    if (result.RedirectUri != null)
                    {
                        return(result);
                    }
                    else
                    {
                        CalendarService = new CalendarService(new BaseClientService.Initializer()
                        {
                            HttpClientInitializer = result.Credential,
                            ApplicationName       = APPLICATION_NAME
                        });
                        // alright
                        return("OK");
                    }
                }
            }
            catch (Exception ex)
            {
                return(ex);
            }

            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.");
            }
        }
    }
示例#6
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);
        }
示例#7
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);
        }
        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
                    });
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["state"] != null)
                {
                    IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(
                        new GoogleAuthorizationCodeFlow.Initializer
                    {
                        ClientSecrets = GetClientConfiguration().Secrets,
                        DataStore     = new FileDataStore(gFolder),
                        Scopes        = new[] { CalendarService.Scope.Calendar }
                    });

                    var uri  = System.Web.HttpContext.Current.Request.Url.ToString(); /*"http://localhost:19594/GoogleCalendarRegistration.aspx";*/
                    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, System.Web.HttpContext.Current.Request["state"]).Result;
                        System.Web.HttpContext.Current.Response.Redirect(oauthState);
                    }
                }

                try
                {
                    if (XmlDoc.HasChildNodes == false)
                    {
                        XmlDoc.Load(AppDomain.CurrentDomain.BaseDirectory + "App_Data\\XMLfile.xml");
                    }
                    //check if the user has logged in
                    if (Session[UserID] != null && string.IsNullOrEmpty(Session[UserID].ToString()) == false)
                    {
                        //if the user is registered
                        if (string.IsNullOrEmpty(XmlDoc.DocumentElement.ChildNodes[0].Attributes[AccessToken].Value.ToString()) == false)
                        {
                            PnlLogin.Visible    = false;
                            PnlRegister.Visible = false;
                            PnlEvents.Visible   = true;

                            TxtStartTime.Text = DateTime.Now.ToString();
                            TxtEndTime.Text   = DateTime.Now.AddHours(2).ToString();

                            //check if event is created or not
                            if (XmlDoc.DocumentElement.SelectSingleNode("//Event").Attributes["EventTitle"].Value == "")
                            {
                                BtnDeleteEvent.Enabled = false;
                            }
                            else
                            {
                                TxtTitle.Text        = XmlDoc.DocumentElement.SelectSingleNode("//Event").Attributes["EventTitle"].Value;
                                TxtStartTime.Text    = XmlDoc.DocumentElement.SelectSingleNode("//Event").Attributes["EventStartTime"].Value;
                                TxtEndTime.Text      = XmlDoc.DocumentElement.SelectSingleNode("//Event").Attributes["EventEndTime"].Value;
                                TxtEventDetails.Text = XmlDoc.DocumentElement.SelectSingleNode("//Event").Attributes["EventDetails"].Value;

                                BtnDeleteEvent.Enabled = true;
                            }
                        }
                        else
                        {
                            PnlLogin.Visible    = false;
                            PnlRegister.Visible = true;
                            PnlEvents.Visible   = false;
                        }
                    }

                    else
                    {
                        PnlLogin.Visible    = true;
                        PnlRegister.Visible = false;
                        PnlEvents.Visible   = false;

                        LblMessage.Text = "Please login";
                    }
                }
                catch { }
            }
            //else
            //{
            //    BtnCreateUpdateEvent_Click(null, null);
            //}
        }
示例#10
0
    // API
    protected void GmailAPI(object sender, EventArgs e)
    {
        String credPath = System.Web.HttpContext.Current.Server.MapPath("/App_Data/GmailAPI");
        String uri      = Request.Url.ToString();
        String user_id  = Util.GetUserId();

        IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(
            new GoogleAuthorizationCodeFlow.Initializer
        {
            ClientSecrets = new ClientSecrets()
            {
                ClientId = "792417557967-mbt9n0cvnnlm01947sh1om351nd9quku.apps.googleusercontent.com", ClientSecret = "9lo8IshXhyIMy8_5jd6YoCNd"
            },
            DataStore = new FileDataStore(credPath, true),
            Scopes    = new String[] { GmailService.Scope.GmailReadonly }
        });

        var code = Request["code"];

        if (String.IsNullOrEmpty(code))
        {
            AuthorizationCodeWebApp.AuthResult AuthResult = new AuthorizationCodeWebApp(flow, uri, uri).AuthorizeAsync(user_id, CancellationToken.None).Result;
            Util.Debug(AuthResult.RedirectUri);
            if (AuthResult.RedirectUri != null)
            {
                // Redirect the user to the authorization server.
                Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('" + AuthResult.RedirectUri + "','_newtab');", true);
            }
            else
            {
                // Create Gmail API service.
                GmailService service = new GmailService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = AuthResult.Credential,
                    ApplicationName       = "My Project"
                });

                // Define parameters of request.
                UsersResource.LabelsResource.ListRequest request = service.Users.Labels.List("me");

                // List labels.
                IList <Google.Apis.Gmail.v1.Data.Label> labels = request.Execute().Labels;
                Response.Write("Labels:");
                if (labels != null && labels.Count > 0)
                {
                    foreach (var labelItem in labels)
                    {
                        Response.Write("    " + labelItem.Name);
                    }
                }
                else
                {
                    Response.Write("No labels found.");
                }
            }
        }
        else
        {
            var token = flow.ExchangeCodeForTokenAsync(user_id, code, uri.Substring(0, uri.IndexOf("?")), CancellationToken.None).Result;

            // Extract the right state.
            var oauthState = AuthWebUtility.ExtracRedirectFromState(flow.DataStore, user_id, Request["state"]).Result;

            Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('" + oauthState + "','_newtab');", true);
        }
    }
        public AnalyticsService Handle(string _userId, string _connectionString, string _googleRedirectUri, string _applicationName, string[] _scopes)
        {
            try
            {
                string                      UserId = _userId;//The user ID wil be for examlpe the users gmail address.
                AnalyticsService            service;
                GoogleAuthorizationCodeFlow flow;
                //use extended class to create google authorization code flow
                flow = new ForceOfflineGoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    DataStore     = new DbDataStore(_connectionString),//DataStore class to save the token in a SQL database.
                    ClientSecrets = new ClientSecrets {
                        ClientId = "XXX-YOUR CLIENTID-XXX", ClientSecret = "XXX-YOURCLIENTSECRET-XXX"
                    },
                    Scopes = _scopes,
                });


                var    uri         = HttpContext.Current.Request.Url.ToString();
                string redirecturi = _googleRedirectUri;    //This is the redirect URL set in google developer console.
                var    code        = HttpContext.Current.Request["code"];
                if (code != null)
                {
                    var token = flow.ExchangeCodeForTokenAsync(UserId, code,
                                                               uri.Substring(0, uri.IndexOf("?")), CancellationToken.None).Result;

                    var test = HttpContext.Current.Request["state"];

                    // Extract the right state.
                    var oauthState = AuthWebUtility.ExtracRedirectFromState(
                        flow.DataStore, UserId, HttpContext.Current.Request["state"]).Result;
                    HttpContext.Current.Response.Redirect(oauthState);
                }
                else
                {
                    var result = new AuthorizationCodeWebApp(flow, redirecturi, uri).AuthorizeAsync(UserId,
                                                                                                    CancellationToken.None).Result;

                    if (result.RedirectUri != null)
                    {
                        // Redirect the user to the authorization server.
                        HttpContext.Current.Response.Redirect(result.RedirectUri);
                    }
                    else
                    {
                        // The data store contains the user credential, so the user has been already authenticated.
                        service = new AnalyticsService(new BaseClientService.Initializer()
                        {
                            HttpClientInitializer = result.Credential,
                            ApplicationName       = _applicationName
                        });
                        return(service);
                    }
                }
                return(null);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#12
0
        /// <summary>
        /// Efetua login OAuth no google e grava dados em banco de dados para não precisar ficar logando a cada acesso
        /// </summary>
        /// <param name="usuarioID">ID do usuário que está logando</param>
        /// <param name="conexaoBanco">String de conexão com banco de dados</param>
        /// <param name="urlRedirecionamento">URL que o google irá redirecionar de volta após o Login</param>
        /// <param name="aplicacaoNome">Nome da aplicação no google console developer</param>
        /// <param name="escopos">Escopos que definem o que será usado do serviço</param>
        /// <returns>Retorna o serviço que será usado</returns>
        public static CalendarService OAuthLogin(string usuarioID, string conexaoBanco, string urlRedirecionamento, string aplicacaoNome, string[] escopos)
        {
            try
            {
                CalendarService service = new CalendarService();

                //Use uma classe extendida para autenticação Google Flow
                GoogleAuthorizationCodeFlow flow;
                flow = new ForceOfflineGoogleAuthorizationCodeFlow(
                    new GoogleAuthorizationCodeFlow.Initializer
                {
                    //Classe GoogleDAO para salvar o token de acesso no banco de dados.
                    DataStore     = new GoogleDAO(conexaoBanco),
                    ClientSecrets = new ClientSecrets {
                        ClientId = "215187720738-qvd9a4kbm69cqd5iuutgekhspg67l8ar.apps.googleusercontent.com", ClientSecret = "96JWX7tgheXLn1pe5QJw968E"
                    },
                    Scopes = escopos
                });


                var uri = Convert.ToString(HttpContext.Current.Request.Url);

                //URL de redirecionamento configurada no painel do google developers console.
                string uriRedirecionamento = urlRedirecionamento;

                if (HttpContext.Current.Request["code"] != null)
                {
                    var token = flow.ExchangeCodeForTokenAsync(usuarioID, HttpContext.Current.Request["code"], uri.Substring(0, uri.IndexOf("?")), CancellationToken.None).Result;

                    // Extrai dados salvos.
                    var oauthState = AuthWebUtility.ExtracRedirectFromState(flow.DataStore, usuarioID, HttpContext.Current.Request["state"]).Result;

                    var dados = new AuthorizationCodeWebApp(flow, uriRedirecionamento, uri).AuthorizeAsync(usuarioID, CancellationToken.None).Result;

                    //Caso já exista no banco de dados o token, o usuário já possui permissão e está logado.
                    service = new CalendarService
                              (
                        new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = dados.Credential,
                        ApplicationName       = aplicacaoNome
                    }
                              );

                    return(service);
                }
                else
                {
                    var dados = new AuthorizationCodeWebApp(flow, uriRedirecionamento, uri).AuthorizeAsync(usuarioID, CancellationToken.None).Result;

                    if (dados.RedirectUri != null)
                    {
                        //Redireciona o usuário para fazer login e dar as permissões
                        HttpContext.Current.Response.Redirect(dados.RedirectUri);
                    }
                    else
                    {
                        //Caso já exista no banco de dados o token, o usuário já possui permissão e está logado.
                        service = new CalendarService
                                  (
                            new BaseClientService.Initializer()
                        {
                            HttpClientInitializer = dados.Credential,
                            ApplicationName       = aplicacaoNome
                        }
                                  );

                        return(service);
                    }
                }

                return(null);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }