/// <summary> /// Creates the google client service implementation for the given google user ID asynchronous. /// </summary> /// <param name="authCode">The authentication code.</param> /// <returns> /// A Google Client Service instance. /// </returns> public async Task <IGoogleClientService> CreateGoogleClientServiceForUserAsync(string authCode) { // TODO make use of data store after testing var dataStore = new GoogleEntityDataStore(_context); using IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow( new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = new ClientSecrets { ClientId = _options.ClientId, ClientSecret = _options.ClientSecret }, Scopes = _options.Scopes, // TODO use entityDataStore DataStore = new FileDataStore("GoogleTokens") }); TokenResponse token = await flow.ExchangeCodeForTokenAsync("USER_ID", authCode, _options.RedirectUri, CancellationToken.None); UserCredential credential = new UserCredential(flow, Environment.UserName, token); // Create service initializer BaseClientService.Initializer initializer = new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = _options.ApplicationName }; return(new GoogleClientService(_logger, initializer)); }
public async Task <GooglePayload> ValidateBearerTokenAsync(string authCode) { var authorizationCodeFlow = new GoogleAuthorizationCodeFlow( new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = new ClientSecrets() { ClientId = _identityOptions.GoogleClientId, ClientSecret = _identityOptions.GoogleClientSecret } }); TokenResponse tokenResponse = await authorizationCodeFlow .ExchangeCodeForTokenAsync("me", authCode, "http://localhost:8080", CancellationToken.None); UserCredential userCredential = new UserCredential(authorizationCodeFlow, "me", tokenResponse); BooksService booksService = new BooksService(new BaseClientService.Initializer { HttpClientInitializer = userCredential }); Bookshelves test = await booksService.Mylibrary.Bookshelves.List().ExecuteAsync(); Payload payload = await ValidateAsync(tokenResponse.IdToken, GetValidationSettings()); return(new GooglePayload(payload, tokenResponse.AccessToken, tokenResponse.RefreshToken)); }
public async Task <ActionResult> RegisterGoogleDrive(string gdCode) { 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 response = await flow.ExchangeCodeForTokenAsync( accountId.ToString(), gdCode, _config.GetValue <string>("GDRedirectURL"), CancellationToken.None ); await _migService.GoogleDriveMigrationAsync(accountId); return(Ok()); }
public void Authorize(string accessCode) { if (IsAuthorized) { return; } GoogleClientSecrets secrets; using (var stream = new FileStream(_configuration.ServiceAccountCredentials, FileMode.Open, FileAccess.Read)) secrets = GoogleClientSecrets.Load(stream); // Use the code exchange flow to get an access and refresh token. IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = secrets.Secrets, Scopes = new [] { DirectoryService.Scope.AdminDirectoryResourceCalendarReadonly, CalendarService.Scope.CalendarReadonly } }); var tokenResponse = flow.ExchangeCodeForTokenAsync("", accessCode, "postmessage", CancellationToken.None).Result; _userCredential = new UserCredential(flow, "me", tokenResponse); IsAuthorized = true; InitializeServices(); }
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 ActionResult GetAuthenticationTokenDrive(string code) { if (String.IsNullOrEmpty(code)) { return(View("Error")); } List <dtoAsuntos> ArchivosCargados = (List <dtoAsuntos>)Session["ArchivosCargados"]; string redirectUrl = $"https://{Request.Url.Host}:{Request.Url.Port}/{Url.Action(nameof(this.GetAuthenticationTokenDrive)).TrimStart('/')}"; 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, }; int UserIdPersona = 0; 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); DriveService service = new DriveService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = Application_Name, ApiKey = "AIzaSyBtEx9nIXbv-C-jEj45iIUZvs-HUP8SCc8" }); var RequestListado = service.Files.List(); RequestListado.Fields = "nextPageToken, files(id,name)"; var response = RequestListado.Execute(); if (response != null && response.Files.Count > 0) { List <dtoAsuntos> Archivos = new List <dtoAsuntos>(); foreach (var file in response.Files) { if (!ArchivosCargados.Select(x => x.NombreArchivo).Contains(file.Name)) { Archivos.Add(new dtoAsuntos { GuidArchivo = file.Id, NombreArchivo = file.Name, Drive = true }); } } Session["ListadoDrive"] = Archivos; } return(RedirectToAction("MisAsuntos")); }
/// <summary> /// Generates user crendentials from a google authorization code. /// </summary> private async Task <UserCredential> GenerateUserCredentialFromAuthorizationCode(string code) { string userTokenKey = Guid.NewGuid().ToString(); TokenResponse token = await flow.ExchangeCodeForTokenAsync( userTokenKey, code, OAuthRedirectUri, CancellationToken.None); UserCredential credential = new UserCredential(flow, userTokenKey, token); return(credential); }
/// <summary> /// Ends the OAuth2.0 authorization process for web applications. /// After successful execution of this method you are able to /// perform actions like upload/download on GStorage object /// </summary> /// <param name="code">code parameter extracted from HttpRequest query string</param> /// <param name="redirectUrl">url to which redirection will be made after successful authorization</param> public virtual void AuthorizeWebAppEnd(string code, string redirectUrl) { if (AuthorizationFlow == null) { throw new NullReferenceException("Authorization not started!"); } var tokenRequest = AuthorizationFlow.ExchangeCodeForTokenAsync(Mail, code, redirectUrl, CancellationToken.None); tokenRequest.Wait(); UserCredential = new UserCredential(AuthorizationFlow, Mail, tokenRequest.Result); }
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")); }
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; } }
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); }
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); }
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); }
/// <summary> /// Exchanges the authorization code for credentials. /// </summary> /// <returns>The <see cref="TokenResponse"/> object that contains the access /// and refresh tokens.</returns> public TokenResponse ExchangeAuthorizationCodeForCredentials() { string authorizationCode = this.context.Request.Query["code"]; Task <TokenResponse> responseTask = flow.ExchangeCodeForTokenAsync(null, authorizationCode, GetCurrentPagePath(), CancellationToken.None); responseTask.Wait(); TokenResponse response = responseTask.Result; // Save the credentials. this.TokenResponse = response; return(response); }
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 }); } } }
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); }
/// <summary> /// Exchanges the authorization code for credentials. /// </summary> /// <returns>The <see cref="TokenResponse"/> object that contains the access /// and refresh tokens.</returns> public TokenResponse ExchangeAuthorizationCodeForCredentials() { string url = page.Request.Url.OriginalString; string authorizationCode = page.Request.QueryString["code"]; Task <TokenResponse> responseTask = flow.ExchangeCodeForTokenAsync(null, authorizationCode, GetCurrentPagePath(), CancellationToken.None); responseTask.Wait(); TokenResponse response = responseTask.Result; // Save the credentials. this.Credentials = new UserCredential(flow, STATE_PARAMETER, response); return(response); }
public ActionResult SignInWithGoogle(string code) { // Use the code exchange flow to get an access and refresh token. IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = GetClientConfiguration().Secrets, Scopes = new[] { Oauth2Service.Scope.PlusLogin, Oauth2Service.Scope.UserinfoProfile, Oauth2Service.Scope.UserinfoEmail } }); var response = flow.ExchangeCodeForTokenAsync("", code, "postmessage", CancellationToken.None).Result; // response.accessToken now should be populated var credential = new UserCredential(flow, "me", response); var oauthSerivce = new Oauth2Service(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "Grid Intranet" }); var userInfo = oauthSerivce.Userinfo.Get().Execute(); var user = _userRepository.GetBy(u => u.Username == userInfo.Email, "AccessRule,Person"); if (user == null) { return(Json(false)); } if (user.AccessRule == null) { return(Json(false)); } if (!user.AccessRule.IsApproved) { return(Json(false)); } // Everything is fine. RecordLoginSucceeded(user); return(Json(true)); }
public async Task <GmailServiceResponse <Token> > GetToken(string code) { var result = new GmailServiceResponse <Token>(); try { var credential = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = new ClientSecrets { ClientId = ClientId, ClientSecret = ClientSecret, }, Scopes = new[] { Google.Apis.Gmail.v1.GmailService.Scope.GmailModify } }); var tokenResponse = await credential.ExchangeCodeForTokenAsync("", code, RedirectUri, CancellationToken.None); var token = new Token() { AccessToken = tokenResponse.AccessToken, ExpiresInSeconds = tokenResponse.ExpiresInSeconds, IdToken = tokenResponse.IdToken, Issued = tokenResponse.Issued, IssuedUtc = tokenResponse.IssuedUtc, RefreshToken = tokenResponse.RefreshToken, Scope = tokenResponse.Scope, TokenType = tokenResponse.TokenType, }; result.Result = token; } catch (Exception ex) { result.Error = ex.Message; } return(result); }
/// <summary> /// 로그인 처리 코드를 가져와 토큰으로 교환 /// </summary> /// <param name="userId"></param> /// <param name="taskCancellationToken"></param> /// <returns></returns> public async Task <UserCredential> AuthorizeAsync(string userId, CancellationToken taskCancellationToken) { // 토큰이 로컬에 저장되어 있으면 저장되어있는 토큰을 불러옴 var token = await flow.LoadTokenAsync(userId, taskCancellationToken).ConfigureAwait(false); // 로컬에 저장되어 있는 토큰이 없으면 실행 if (token == null || (token.RefreshToken == null && token.IsExpired(flow.Clock))) { var authorizationCode = await loginform.GetAuthenticationToken(flow.ClientSecrets.ClientId, flow.Scopes, userId, GoogleAuthConsts.AuthorizationUrl, GoogleAuthConsts.InstalledAppRedirectUri, LoginOption.GoogleDrive); if (string.IsNullOrEmpty(authorizationCode)) { return(null); } //Logger.Debug("Received \"{0}\" code", response.Code); // 코드를 기반으로 토큰을 얻어옴 token = await flow.ExchangeCodeForTokenAsync(userId, authorizationCode, GoogleAuthConsts.InstalledAppRedirectUri, taskCancellationToken).ConfigureAwait(false); } return(new UserCredential(flow, userId, token)); }
public async Task <LinkResult> LinkGoogle(string state, string code) { var configState = await repository.GetConfigState(state); 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" }, }); Google.Apis.Auth.OAuth2.Responses.TokenResponse tokenResponse; try { tokenResponse = await flow.ExchangeCodeForTokenAsync(null, code, options.GoogleRedirectUri, CancellationToken.None); } catch (TokenResponseException e) { throw new CalendarConfigurationException($"Google: Could not redeem authorization code: {e.Error.ErrorDescription}", e); } var id = await repository.AddGoogleTokens(configState.UserId, new TokenResponse() { access_token = tokenResponse.AccessToken, refresh_token = tokenResponse.RefreshToken, expires_in = (int)tokenResponse.ExpiresInSeconds.Value }); return(new LinkResult() { RedirectUri = configState.RedirectUri, Id = id }); }
// called by .auth command - receive auth code, exchange it for token, log in public async Task GetTokenAndLogin(string userInput, SocketCommandContext context) { // split auth code from the url that the user passes to this function var authCode = userInput.Split('=', '&')[1]; // grab server by id of current guild via context var server = Servers.ServerList.Find(x => x.DiscordServerObject == context.Guild); var credentialPath = $@"{_credentialPathPrefix}/{server.ServerId}"; // build code flow manager to get token using (var stream = new FileStream(_filePath, FileMode.Open, FileAccess.Read)) { var flowManager = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = GoogleClientSecrets.Load(stream).Secrets, Scopes = _scopes, }); // retrieve token using authentication url var token = flowManager.ExchangeCodeForTokenAsync(_userId, authCode, _redirectUri, CancellationToken.None).Result; // save user credentials var fileDataStore = new FileDataStore(credentialPath, true); await fileDataStore.StoreAsync("token", token); } string resultMessage = ":white_check_mark: Authorization successful. Get your calendar ID and run ```.calendarid {id}``` to finish setup." + "Your calendar ID can be found by going to your raid calendar's settings, and scrolling to the \"Integrate Calendar\" section."; await _interactiveService.ReplyAndDeleteAsync(context, resultMessage, false, null, TimeSpan.FromMinutes(1)); // log in using our new token await Login(server); }
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); //} }
public async Task <ActionResult> EnviarEmail(string code, string state) { string mensajeExtra = ""; try { TokenResponse token = null; string[] splitState = state.Split('|'); int idTienda = 0; int idUsuarioTienda = 0; int idUsuario = 0; int idDocumento = 0; string nombreDocumentoPDF = ""; string nombreDestinatarioDefault = "-"; Tienda tienda = null; //OBTENER VARIABLES idTienda = Convert.ToInt32(splitState[0]); idDocumento = Convert.ToInt32(splitState[1]); //Puede ser "", Nombre del pdf incluye idEmpresa: 15/nombrePDF.pdf nombreDocumentoPDF = splitState[2]; idUsuarioTienda = Convert.ToInt32(splitState[3]); if (tienda == null) { tienda = db.Tienda.Where(e => e.Id == idTienda).FirstOrDefault(); } Usuario usuario = db.Usuarios.Where(u => u.Id == idUsuario).FirstOrDefault(); //FuncionesGlobalesControllers.RefreshSession(this, empresa, user); try { if (credentialClienteNormal == null) { mensajeExtra += "null1"; } CrearCredencialNormal(); if (credentialClienteNormal == null) { mensajeExtra += "null2"; } token = await credentialClienteNormal.ExchangeCodeForTokenAsync("", code, redirectUri, CancellationToken.None); } catch (Exception e) { if (code == null) { code = "null"; } //ReporteErrores.CrearReporteError(db, // "idEmpresa: " + idEmpresa // + "pista: " + pista // + " nombreDocumento: " + nombreDocumentoPDF // + " authCode: " + code // + " msj extra: " + mensajeExtra // + " \n redirectUri: " + redirectUri // + " \n sumario error: " + e.Message // + " \n error completo: " + e.ToString() // ); //TempData["msgEmail"] = "Aviso: No se pudo completar la acción. Sistema de correo electrónico no disponible."; //return RedirectToAction("ResultadoMail", new { tipo = (int)tipo, msgTest = "5" }); } LoginConToken(token, null, TipoTokenLogin.EnviaEmailNormal); Email email = new Email(); email.IdTienda = tienda.Id; email.Token = token.AccessToken; //email.EmailDesde = emailUsuario; email.EmailPara = ""; email.ClienteId = idUsuario; email.NombreDestinatario = nombreDestinatarioDefault; email.Tema = ""; email.Mensaje = ""; email.IdDocumento = 0; email.CodigoDocumento = ""; email.Cotizacion = null; email.IdUsuario = idUsuarioTienda; email.NombreDocumento = nombreDocumentoPDF; email.PathDocumentoPDF = ""; string nombreCarpeta = ""; nombreCarpeta = "PDFEmpresas"; Cotizacion cotizacion = tienda.Cotizaciones.Where(c => c.Id == idDocumento).FirstOrDefault(); email.ClienteId = cotizacion.Usuario.Id; email.IdDocumento = cotizacion.Id; email.CodigoDocumento = cotizacion.Codigo; email.EmailPara = cotizacion.Usuario.Email; email.NombreDestinatario = cotizacion.Usuario.NombreCompleto; email.Cotizacion = cotizacion; email.Tema = cotizacion.Referencia + " " + cotizacion.Codigo; email.PathDocumentoPDF = Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/img/" + nombreCarpeta + "/" + idTienda), nombreDocumentoPDF); ViewBag.IdTienda = idTienda; ViewBag.NombreCarpeta = nombreCarpeta; return(View(email)); } 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" })); } }
// 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); } }
/// <summary> /// Processes the request based on the path. /// </summary> /// <param name="context">Contains the request and response.</param> public void ProcessRequest(HttpContext context) { // Redirect base path to signin. if (context.Request.Path.EndsWith("/")) { context.Response.RedirectPermanent("signin.ashx"); } // This is reached when the root document is passed. Return HTML // using index.html as a template. if (context.Request.Path.EndsWith("/signin.ashx")) { String state = (String)context.Session["state"]; // Store a random string in the session for verifying // the responses in our OAuth2 flow. if (state == null) { Random random = new Random((int)DateTime.Now.Ticks); StringBuilder builder = new StringBuilder(); for (int i = 0; i < 13; i++) { builder.Append(Convert.ToChar( Convert.ToInt32(Math.Floor( 26 * random.NextDouble() + 65)))); } state = builder.ToString(); context.Session["state"] = state; } // Render the templated HTML. String templatedHTML = File.ReadAllText( context.Server.MapPath("index.html")); templatedHTML = Regex.Replace(templatedHTML, "[{]{2}\\s*APPLICATION_NAME\\s*[}]{2}", APP_NAME); templatedHTML = Regex.Replace(templatedHTML, "[{]{2}\\s*CLIENT_ID\\s*[}]{2}", secrets.ClientId); templatedHTML = Regex.Replace(templatedHTML, "[{]{2}\\s*STATE\\s*[}]{2}", state); context.Response.ContentType = "text/html"; context.Response.Write(templatedHTML); return; } if (context.Session["authState"] == null) { // The connect action exchanges a code from the sign-in button, // verifies it, and creates OAuth2 credentials. if (context.Request.Path.Contains("/connect")) { // Get the code from the request POST body. StreamReader sr = new StreamReader( context.Request.InputStream); string code = sr.ReadToEnd(); string state = context.Request["state"]; // Test that the request state matches the session state. if (!state.Equals(context.Session["state"])) { context.Response.StatusCode = 401; return; } // Use the code exchange flow to get an access and refresh token. IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = secrets, Scopes = SCOPES }); token = flow.ExchangeCodeForTokenAsync("", code, "postmessage", CancellationToken.None).Result; // Create an authorization state from the returned token. context.Session["authState"] = token; // Get tokeninfo for the access token if you want to verify. Oauth2Service service = new Oauth2Service( new Google.Apis.Services.BaseClientService.Initializer()); Oauth2Service.TokeninfoRequest request = service.Tokeninfo(); request.AccessToken = token.AccessToken; Tokeninfo info = request.Execute(); string gplus_id = info.UserId; } else { // No cached state and we are not connecting. context.Response.StatusCode = 400; return; } } else if (context.Request.Path.Contains("/connect")) { // The user is already connected and credentials are cached. context.Response.ContentType = "application/json"; context.Response.StatusCode = 200; context.Response.Write(JsonConvert.SerializeObject("Current user is already connected.")); return; } else { // Register the authenticator and construct the Plus service // for performing API calls on behalf of the user. token = (TokenResponse)context.Session["authState"]; IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = secrets, Scopes = SCOPES }); UserCredential credential = new UserCredential(flow, "me", token); bool success = credential.RefreshTokenAsync(CancellationToken.None).Result; token = credential.Token; ps = new PlusService( new Google.Apis.Services.BaseClientService.Initializer() { ApplicationName = ".NET Quickstart", HttpClientInitializer = credential }); } // Perform an authenticated API request to retrieve the list of // people that the user has made visible to the app. if (context.Request.Path.Contains("/people")) { // Get the PeopleFeed for the currently authenticated user. PeopleFeed pf = ps.People.List("me", PeopleResource.ListRequest.CollectionEnum.Visible).Execute(); // This JSON, representing the people feed, will later be // parsed by the JavaScript client. string jsonContent = Newtonsoft.Json.JsonConvert.SerializeObject(pf); context.Response.ContentType = "application/json"; context.Response.Write(jsonContent); return; } // Disconnect the user from the application by revoking the tokens // and removing all locally stored data associated with the user. if (context.Request.Path.Contains("/disconnect")) { // Perform a get request to the token endpoint to revoke the // refresh token. token = (TokenResponse)context.Session["authState"]; string tokenToRevoke = (token.RefreshToken != null) ? token.RefreshToken : token.AccessToken; WebRequest request = WebRequest.Create( "https://accounts.google.com/o/oauth2/revoke?token=" + token); WebResponse response = request.GetResponse(); // Remove the cached credentials. context.Session["authState"] = null; // You could reset the state in the session but you must also // reset the state on the client. // context.Session["state"] = null; context.Response.Write( response.GetResponseStream().ToString().ToCharArray()); return; } }
public async Task <ActionResult> DownloadFileDrive(string code) { List <dtoAsuntos> Archivos = (List <dtoAsuntos>)Session["ArchivosDownloadDrive"]; try { string IdUsuario = User.Identity.GetUserId(); string redirectUrl = $"https://{Request.Url.Host}:{Request.Url.Port}/{Url.Action(nameof(this.DownloadFileDrive)).TrimStart('/')}"; 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, }; int UserIdPersona = 0; 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); DriveService service = new DriveService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = Application_Name, ApiKey = "AIzaSyBtEx9nIXbv-C-jEj45iIUZvs-HUP8SCc8" }); foreach (dtoAsuntos FileId in Archivos) { FilesResource.GetRequest request = service.Files.Get(FileId.GuidArchivo); string destPath = Path.Combine(Server.MapPath("~/App_Data"), FileId.NombreArchivo); using (FileStream filestream = new FileStream(destPath, FileMode.Create, FileAccess.Write)) { request.MediaDownloader.ProgressChanged += (IDownloadProgress progress) => { switch (progress.Status) { case DownloadStatus.Downloading: { Debug.WriteLine(progress.BytesDownloaded); break; } case DownloadStatus.Completed: { Debug.WriteLine("Download complete."); break; } case DownloadStatus.Failed: { Debug.WriteLine("Download failed."); break; } } }; await request.DownloadAsync(filestream); } byte[] Blob = System.IO.File.ReadAllBytes(destPath); FileId.Archivo = Blob; FileId.GuidArchivo = String.Empty; FileId.IdUsuario = IdUsuario; } Tuple <bool, string> _result = new BALAsuntos().UpdateArchivosAsuntos(Archivos); foreach (dtoAsuntos file in Archivos) { string destPath = Path.Combine(Server.MapPath("~/App_Data"), file.NombreArchivo); System.IO.File.Delete(destPath); } Session["ArchivosDownloadDrive"] = null; if (_result.Item1) { Session["ArchivosDownloadDrive"] = true; } } catch (Exception ex) { } return(RedirectToAction("MisAsuntos")); }
public async Task <Response> GoogleLogin(string code) { var response = new Response(); try { var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer() { ClientSecrets = new ClientSecrets() { ClientId = _configuration["GoogleClientId"], ClientSecret = _configuration["GoogleClientSecret"] }, Scopes = new[] { "email", "profile" }, }); var token = await flow.ExchangeCodeForTokenAsync("user", code, _configuration["GoogleRedirectUri"], CancellationToken.None); var payload = (await GoogleJsonWebSignature.ValidateAsync(token.IdToken, new GoogleJsonWebSignature.ValidationSettings())); var appUser = await _userManager.FindByNameAsync(payload.Email); if (appUser != null) { appUser.UserName = payload.Email; appUser.AvatarUrl = payload.Picture; await _signInManager.SignInAsync(appUser, false); response = new DataResponse <object>() { Data = GenerateJwtToken(appUser), Success = true }; } else { //new user var user = new ApplicationUser { //hack for now - force users to activate email before logging in? UserName = payload.Email, Email = payload.Email, AvatarUrl = payload.Picture }; var identityResult = await _userManager.CreateAsync(user); if (identityResult.Succeeded) { await _signInManager.SignInAsync(user, false); response = new DataResponse <object>() { Data = GenerateJwtToken(user), Success = true }; } else { foreach (IdentityError Error in identityResult.Errors) { response.AddError("*", Error.Description); } } } } catch (Exception e) { response.AddError("*", "Error authenticating with Google"); } return(response); }
public async Task <bool> Handle(LoginGooglePlusUserRequest request) { if (request.SecurityContext.GetAuthenticatedUser() != null) { // The user is already connected return(true); } // Use the code exchange flow to get an access and refresh token. IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = GooglePlusSecrets.Secrets, Scopes = GooglePlusSecrets.Scopes }); var token = await flow.ExchangeCodeForTokenAsync( "", request.Code, "postmessage", CancellationToken.None); // Get tokeninfo for the access token if you want to verify. var service = new Oauth2Service( new Google.Apis.Services.BaseClientService.Initializer()); var oauthRequest = service.Tokeninfo(); oauthRequest.AccessToken = token.AccessToken; var info = oauthRequest.Execute(); // Register the authenticator and construct the Plus service // for performing API calls on behalf of the user. var credential = new UserCredential(flow, "me", token); await credential.RefreshTokenAsync(CancellationToken.None); token = credential.Token; var plusService = new PlusService( new Google.Apis.Services.BaseClientService.Initializer { ApplicationName = "DLVoter", HttpClientInitializer = credential }); var me = await plusService.People.Get("me").ExecuteAsync(); var user = new User { FirstName = me.Name.GivenName, LastName = me.Name.FamilyName, ExternalCorrelationId = new ExternalCorrelationId { Value = info.UserId }, Type = UserType.GooglePlus }; user.OAuthToken = new OAuthToken { Value = token?.RefreshToken ?? token?.AccessToken }; request.SecurityContext.SetAuthenticatedUser(user); // ToDo: Add or update user in database return(true); }
public async Task <Response> GoogleLogin(OAuthLoginDto loginDto) { var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer() { ClientSecrets = new ClientSecrets() { ClientId = _configuration["GoogleClientId"], ClientSecret = _configuration["GoogleClientSecret"] }, Scopes = new[] { "email", "profile" }, }); try { //Exchange / validate code with Google var googleToken = await flow.ExchangeCodeForTokenAsync("user", loginDto.Code, _configuration["GoogleRedirectUri"], CancellationToken.None); var payload = (await GoogleJsonWebSignature.ValidateAsync(googleToken.IdToken, new GoogleJsonWebSignature.ValidationSettings())); var appUser = await _userManager.FindByNameAsync(payload.Email); //Check if this user has signed in before (if we have a AspNetUser record for them) if (appUser != null) { if (appUser.AuthType != AuthType.Google) { return(new Response().WithError("*", "Account already authenticated with " + appUser.AuthType.ToString())); } if (appUser.AvatarUrl != payload.Picture) { appUser.AvatarUrl = payload.Picture; await _userManager.UpdateAsync(appUser); } //await _signInManager.SignInAsync(appUser, false); } //No existing sign ins for this user, let's create a record for them else { appUser = new ApplicationUser { //hack for now - force users to activate email before logging in? UserName = payload.Email, Email = payload.Email, DisplayName = payload.GivenName, AuthType = AuthType.Google, AvatarUrl = payload.Picture }; var result = await _userManager.CreateAsync(appUser); if (!result.Succeeded) { return(new Response() .WithErrors(result.Errors .Select(error => new Response.Error() { Key = error.Code == "DuplicateUserName" ? "email" : "*", Msg = error.Code == "DuplicateUserName" ? "Email already in use" : error.Description }).ToList())); } } //Create JWT and cookie for user and return success var token = GenerateJwt(appUser).ToString(); GenerateCookie(token); return(new DataResponse <TokenDto>() .WithData(new TokenDto() { Token = token })); } catch (Exception e) { return(new Response() .WithError("*", "Error authenticating with Google: " + e.Message)); } }