sgcIndy XOAuth2 Delphi

· Componentes

A partir do sgcIndy 2024.5.0, o mecanismo de autenticação XOAuth2 é suportado. O mecanismo SASL XOAUTH2 é utilizado com os comandos IMAP AUTHENTICATE, POP AUTH e SMTP AUTH. Esse mecanismo permite o uso de Access Tokens OAuth 2.0 para autenticar em uma conta Gmail do usuário, por exemplo.

TIdSASLXOAuth2

O TIdSASLXOAuth2 possui o evento OnAuthenticate, que é chamado antes da autorização ser realizada. O evento tem 2 parâmetros:


Se você quiser enviar um e-mail usando o componente TIdSMTP, basta adicionar o componente TIdSASLXOAuth2 como um novo SASLMechanism.
xOAuth2 := TIdSASLXOAUTH2.Create(nil);
smtp := TIdSMTP.Create(nil);
...
smtp.AuthType := satSASL;
smtp.SASLMechanisms.Clear;
smtp.SASLMechanisms.Add.SASL := xoauth2; 

Após configurar os componentes SMTP e XOAuth2, envie um e-mail usando o componente SMTP e quando a autorização for necessária o evento OnAuthenticate é chamado. Basta definir aqui o Username e o Access Token.

procedure OnXOAuth2Authenticate(Sender: TObject; var Username,
    Token: string);
begin
  Token := 'OAuth2 Access Token';
  Username := 'your mail account';
end; 

OAuth2 Client

O OAuth2 Access Token pode ser obtido usando o TsgcHTTP_OAuth2_Client da biblioteca sgcWebSockets.

Veja abaixo um exemplo de como configurar o cliente OAuth2 para obter um OAuth2 Access Token da sua conta Google.

  OAuth2 := TsgcHTTP_OAuth2_Client.Create(nil);
  OAuth2.OnAfterAccessToken := OnOAuth2AfterAccessTokenEvent;
  OAuth2.OAuth2Options.GrantType := auth2CodePKCE;
  OAuth2.LocalServerOptions.IP := '127.0.0.1';
  OAuth2.LocalServerOptions.Port := 0;
  OAuth2.AuthorizationServerOptions.AuthURL := 'https://accounts.google.com/o/oauth2/auth';
  OAuth2.AuthorizationServerOptions.TokenURL := 'https://accounts.google.com/o/oauth2/token';
  OAuth2.AuthorizationServerOptions.Scope.Text := 'https://mail.google.com/';
  OAuth2.OAuth2Options.ClientId := '<your oauth2 client id>';
  OAuth2.OAuth2Options.ClientSecret := '<your oauth2 client secret>';
  OAuth2.Start;
procedure OnOAuth2AfterAccessTokenEvent(Sender: TObject; const
    Access_Token, Token_Type, Expires_In, Refresh_Token, Scope, RawParams:
    String; var Handled: Boolean);
begin
  ShowMessage(Access_Token);
end; 

Demo Delphi XOAuth2

Veja abaixo um demo que mostra o componente XOAuth2 com o OAuth2 Client da biblioteca sgcWebSockets para enviar um e-mail usando o protocolo SMTP. Selecione a aba XOAuth2 para usar esse tipo de autenticação e preencha os campos: 

  1. Username
  2. OAuth2 Client Id
  3. OAuth2 Client Secret
  4. Address to send the email
});