Configuración del acceso a API OAuth 2.0 para servicios de Google
Crear un proyecto en Google Developer Console para acceso a API
Crear un proyecto en Google Developer Console es un paso esencial para acceder y utilizar las APIs de Google en sus aplicaciones. Este proceso implica configurar un proyecto, aceptar los términos, verificar su identidad y configurar los ajustes de la API según sus necesidades. Los siguientes pasos le guiarán a través del proceso de creación de un proyecto y la obtención de las credenciales necesarias para servicios como las APIs de Calendar y Contacts.
Pasos para crear un proyecto en Google Developer Console
- Visite el enlace https://cloud.google.com/console/project e inicie sesión con sus credenciales de Gmail
![]() |
|---|
- Marque la casilla "He leído y acepto todos los Términos de Servicio de los productos de Google Cloud Platform." y presione el botón Crear
![]() |
|---|
- Se solicitará "Verificación SMS". Presione el botón continuar:
![]() |
|---|
- Introduzca el nombre de su país y el número de móvil. Presione el botón: Enviar código de verificación
![]() |
|---|
- Introduzca el código de verificación recibido en su móvil.
![]() |
|---|
- En la lista APIs & auth \ APIs, active el estado de Calendar API y Contacts API. Desactive TODAS las demás.
![]() |
|---|
- En APIs & auth -> Credenciales, presione el botón "CREAR NUEVO CLIENT ID" bajo la sección "OAuth". Seleccione "Aplicación instalada" y "Otro" entre las opciones dadas, y presione el botón "Crear Client ID". Anote aquí el Client ID y el Client Secret que se usarán en los ejemplos de código de esta sección.
![]() |
|---|
Integración segura de Google OAuth 2.0
Al trabajar con Google OAuth 2.0 en Aspose.Email para .NET, necesitará las siguientes clases:
-
Clase GoogleOAuthHelper - Simplifica el proceso de autenticación de un usuario de Google y la obtención de los tokens necesarios para interactuar con las APIs de Google, como Calendar, Contacts y Gmail.
-
Clase GoogleUser - Está diseñada para encapsular y gestionar las credenciales necesarias para que un usuario se autentique e interactúe con los servicios de Google, específicamente APIs que requieren autenticación OAuth 2.0 como Google Calendar.
-
Clase TokenResponse - Es un modelo diseñado para representar y manejar los datos de respuesta de un punto final de token OAuth 2.0, donde se obtienen tokens de acceso a cambio de autorización.
En los siguientes artículos encontrará ejemplos de código que demuestran cómo usar estas clases en el entorno .NET para establecer una interacción segura con los servicios OAuth 2.0.
Autenticación OAuth 2.0 con la clase GoogleOAuthHelper
La clase gestiona la creación de la URL de código de autorización, la generación de desafíos de código y la obtención de tokens de acceso y actualización. Al usar GoogleOAuthHelper, los desarrolladores pueden optimizar el flujo OAuth 2.0, garantizando una comunicación segura y eficiente con los servicios de Google. El siguiente fragmento de código muestra cómo implementar el GoogleOAuthHelper la clase en un proyecto:
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
/// <summary>
/// Developer console:
/// https://console.cloud.google.com/projectselector2
/// Documentation:
/// https://developers.google.com/identity/protocols/oauth2/native-app
/// </summary>
internal class GoogleOAuthHelper
{
public const string AUTHORIZATION_URL = "https://accounts.google.com/o/oauth2/v2/auth";
public const string TOKEN_REQUEST_URL = "https://oauth2.googleapis.com/token";
public const string REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
public const string REDIRECT_TYPE = "code";
public static string codeVerifier;
public static string codeChallenge;
public static CodeChallengeMethod codeChallengeMethod = CodeChallengeMethod.S256;
public const string SCOPE =
"https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar" + // Calendar
"+" +
"https%3A%2F%2Fwww.google.com%2Fm8%2Ffeeds%2F" + // Contacts
"+" +
"https%3A%2F%2Fmail.google.com%2F"; // IMAP & SMTP
static GoogleOAuthHelper()
{
CreateCodeVerifier();
CreateCodeChallenge();
}
internal static string CreateCodeVerifier()
{
string allowedChars = "0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz-._~";
const int minLength = 43;
const int maxLength = 128;
Random random = new Random();
int length = minLength + random.Next(maxLength - minLength);
List<char> codeVerifierChars = new List<char>();
for (int i = 0; i < length; i++)
{
int index = random.Next(allowedChars.Length);
codeVerifierChars.Add(allowedChars[index]);
}
return codeVerifier = string.Join("", codeVerifierChars.ToArray());
}
internal static string CreateCodeChallenge()
{
if (codeChallengeMethod == CodeChallengeMethod.Plain)
return codeChallenge = codeVerifier;
byte[] hashValue = null;
using (SHA256 sha256 = SHA256.Create())
hashValue = sha256.ComputeHash(Encoding.ASCII.GetBytes(codeVerifier));
string b64 = Convert.ToBase64String(hashValue);
b64 = b64.Split('=')[0];
b64 = b64.Replace('+', '-');
b64 = b64.Replace('/', '_');
return codeChallenge = b64;
}
internal static string GetAuthorizationCodeUrl(GoogleUser user)
{
return GetAuthorizationCodeUrl(user, SCOPE, REDIRECT_URI, REDIRECT_TYPE);
}
internal static string GetAuthorizationCodeUrl(
GoogleUser user, string scope, string redirectUri, string responseType)
{
string state = System.Web.HttpUtility.UrlEncode(Guid.NewGuid().ToString());
string approveUrl = AUTHORIZATION_URL +
$"?client_id={user.ClientId}&redirect_uri={redirectUri}&response_type={responseType}&scope={scope}&" +
$"code_challenge={codeChallenge}&code_challenge_method={codeChallengeMethod.ToString()}&" +
$"state={state}";
return approveUrl;
}
internal static TokenResponse GetAccessTokenByRefreshToken(GoogleUser user)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(TOKEN_REQUEST_URL);
request.CookieContainer = new CookieContainer();
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string clientId = System.Web.HttpUtility.UrlEncode(user.ClientId);
string clientSecret = System.Web.HttpUtility.UrlEncode(user.ClientSecret);
string refreshToken = System.Web.HttpUtility.UrlEncode(user.RefreshToken);
string grantType = System.Web.HttpUtility.UrlEncode("refresh_token");
string encodedParameters = $"client_id={clientId}&client_secret={clientSecret}&refresh_token={refreshToken}&grant_type={grantType}";
byte[] requestData = Encoding.UTF8.GetBytes(encodedParameters);
request.ContentLength = requestData.Length;
if (requestData.Length > 0)
using (Stream stream = request.GetRequestStream())
stream.Write(requestData, 0, requestData.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string responseText = null;
using (TextReader reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
responseText = reader.ReadToEnd();
TokenResponse tokensResponse = JsonConvert.DeserializeObject<TokenResponse>(responseText);
return tokensResponse;
}
internal static TokenResponse GetAccessTokenByAuthCode(string authorizationCode, GoogleUser user)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(TOKEN_REQUEST_URL);
request.CookieContainer = new CookieContainer();
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string clientId = System.Web.HttpUtility.UrlEncode(user.ClientId);
string clientSecret = System.Web.HttpUtility.UrlEncode(user.ClientSecret);
string authCode = System.Web.HttpUtility.UrlEncode(authorizationCode);
string redirectUri = System.Web.HttpUtility.UrlEncode(REDIRECT_URI);
string grantType = System.Web.HttpUtility.UrlEncode("authorization_code");
string encodedParameters = $"client_id={clientId}&client_secret={clientSecret}&code={authCode}&code_verifier={codeVerifier}&redirect_uri={redirectUri}&grant_type={grantType}";
byte[] requestData = Encoding.UTF8.GetBytes(encodedParameters);
request.ContentLength = requestData.Length;
if (requestData.Length > 0)
using (Stream stream = request.GetRequestStream())
stream.Write(requestData, 0, requestData.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string responseText = null;
using (TextReader reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
responseText = reader.ReadToEnd();
TokenResponse tokensResponse = JsonConvert.DeserializeObject<TokenResponse>(responseText);
return tokensResponse;
}
public enum CodeChallengeMethod
{
S256,
Plain
}
}
Google OAuth Helper debe usarse de la siguiente manera:
- Primero debe generarse una URL de código de autorización.
- Abra la URL en un navegador y complete todas las operaciones. Como resultado, recibirá un código de autorización.
- Utilice el código de autorización para recibir un token de actualización.
- Cuando existe el token de actualización, puede usarlo para recuperar tokens de acceso.
GoogleUser user = new GoogleUser(email, password, clientId, clientSecret);
string authUrl = GoogleOAuthHelper.GetAuthorizationCodeUrl(user);
Console.WriteLine("Go to the following URL and get your authorization code:");
Console.WriteLine(authUrl);
Console.WriteLine();
Console.WriteLine("Enter the authorization code:");
string authorizationCode = Console.ReadLine();
Console.WriteLine();
TokenResponse tokenInfo = GoogleOAuthHelper.GetAccessTokenByAuthCode(authorizationCode, user);
Console.WriteLine("The refresh token has been received:");
Console.WriteLine(tokenInfo.RefreshToken);
Console.WriteLine();
user.RefreshToken = tokenInfo.RefreshToken;
tokenInfo = GoogleOAuthHelper.GetAccessTokenByRefreshToken(user);
Console.WriteLine("The new access token has been received:");
Console.WriteLine(tokenInfo.AccessToken);
Console.WriteLine();
Clase GoogleUser para autenticación OAuth 2.0
El siguiente fragmento de código muestra cómo implementar el GoogleUser clase:
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
public class GoogleUser
{
public GoogleUser(string email, string password, string clientId, string clientSecret)
: this(email, password, clientId, clientSecret, null)
{
}
public GoogleUser(string email, string password, string clientId, string clientSecret, string refreshToken)
{
Email = email;
Password = password;
ClientId = clientId;
ClientSecret = clientSecret;
RefreshToken = refreshToken;
}
public readonly string Email;
public readonly string Password;
public readonly string ClientId;
public readonly string ClientSecret;
public string RefreshToken;
}
Autenticar con OAuth 2.0 usando la clase TokenResponse
El siguiente fragmento de código muestra cómo el TokenResponse La clase puede implementarse:
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
using Newtonsoft.Json;
public class TokenResponse
{
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "access_token", Required = Required.Default)]
public string AccessToken { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "token_type", Required = Required.Default)]
public string TokenType { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "expires_in", Required = Required.Default)]
public int ExpiresIn { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "refresh_token", Required = Required.Default)]
public string RefreshToken { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "scope", Required = Required.Default)]
public string Scope { get; set; }
}






