sgcIndy XOAuth2 Delphi

· Componenten

Vanaf sgcIndy 2024.5.0 wordt het XOAuth2-authenticatiemechanisme ondersteund. Het SASL XOAUTH2-mechanisme voor gebruik met de IMAP AUTHENTICATE-, POP AUTH- en SMTP AUTH-commando's. Dit mechanisme maakt het mogelijk om OAuth 2.0 Access Tokens te gebruiken om bijvoorbeeld te authenticeren bij het Gmail-account van een gebruiker.

TIdSASLXOAuth2

De TIdSASLXOAuth2 heeft de event OnAuthenticate, die wordt aangeroepen voordat de autorisatie wordt uitgevoerd. De event heeft 2 parameters:


Als je een e-mail wilt versturen met de TIdSMTP-component, voeg dan het TIdSASLXOAuth2-component toe als nieuw SASLMechanism.
xOAuth2 := TIdSASLXOAUTH2.Create(nil);
smtp := TIdSMTP.Create(nil);
...
smtp.AuthType := satSASL;
smtp.SASLMechanisms.Clear;
smtp.SASLMechanisms.Add.SASL := xoauth2; 

Nadat je de SMTP- en XOAuth2-componenten hebt geconfigureerd, verstuur je een e-mail met de SMTP-component en zodra autorisatie nodig is, wordt de event OnAuthenticate aangeroepen. Stel hier gewoon de Username en het Access Token in.

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

OAuth2-client

Het OAuth2 Access Token kan worden verkregen met de TsgcHTTP_OAuth2_Client uit de sgcWebSockets-bibliotheek.

Hieronder vind je een voorbeeld van hoe je de OAuth2-client configureert om een OAuth2 Access Token op te halen vanuit je Google-gebruikersaccount.

  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; 

Delphi XOAuth2-demo

Hieronder vind je een demo waarin het XOAuth2-component samen met de OAuth2-client uit de sgcWebSockets-bibliotheek wordt gebruikt om een e-mail te versturen via het SMTP-protocol. Selecteer het tabblad XOAuth2 om dit type authenticatie te gebruiken en vul de velden in: 

  1. Username
  2. OAuth2 Client Id
  3. OAuth2 Client Secret
  4. Adres om de e-mail naartoe te versturen
});