OAuth2 是 Google 等多家公司使用的常见授权方法。当您想要针对 Google 服务器进行身份验证以使用其任何 API 时,通常需要使用 OAuth2 进行身份验证。
sgcWebSockets 在 HTTP/2 客户端下支持 OAuth2,有一个名为 Authentication.Token.OAuth 的属性,您必须将 TsgcHTTP_OAuth2 的实例分配给它。
为了连接到 Google API,我们需要创建一个 TsgcHTTP_OAuth2 的实例并填写以下数据:
TsgcHTTP_OAuth1.AuthorizationServerOptions.AuthURL := 'https://accounts.google.com/o/oauth2/auth';
TsgcHTTP_OAuth1.AuthorizationServerOptions.TokenURL := 'https://accounts.google.com/o/oauth2/token';
TsgcHTTP_OAuth1.LocalServerOptions.IP := '127.0.0.1';
TsgcHTTP_OAuth1.LocalServerOptions.Port := 8080;
TsgcHTTP_OAuth1.OAuth2Options.ClientId := 'your client id';
TsgcHTTP_OAuth1.OAuth2Options.ClientSecret := 'your client secret';
填写完 OAuth2 客户端组件后,创建一个新的 TsgcHTTP2Client 实例,并将 OAuth2 组件赋值给 HTTP/2 客户端。
TsgcHTTP2Client1.Authentication.Token.OAuth := TsgcHTTP_OAuth1;
最后,发起请求以获取账户 yourname@gmail.com 的消息列表。
oStream := TStringStream.Create('');
Try
TsgcHTTP2Client1.Get('https://gmail.googleapis.com/gmail/v1/users/yourname@gmail.com/messages', oStream);
ShowMessage(oStream.DataString);
Finally
oStream.Free;
End;