1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| var
RESTClient: TRESTClient;
RESTRequest: TRESTRequest;
OAuth2_Dynamics365: TOAuth2Authenticator;
Source: TStringStream;
ReponseContent: TStringStream;
JSONObject: System.JSON.TJSONObject;
ATenantID, AClientID, AClientSecret, ARedirection, AResourceURI, AToken, Scope, Params, LoginURL: string;
begin
ATenantID := '... cf Azure ...';
AClientID := '... cf Azure ...';
AClientSecret := '... cf Azure ...';
ARedirection := System.NetEncoding.TURLEncoding.URL.Encode('https://login.microsoftonline.com/common/oauth2/nativeclient');
AResourceURI := 'https://graph.microsoft.com/v1.0/me/messages';
Scope := 'https://graph.microsoft.com/.default' ; /// 'User.Read'; // Mail.Read'; // https://graph.microsoft.com/v1.0/me/messages
//Scope := 'User.Read'; // Mail.Read'; // https://graph.microsoft.com/v1.0/me/messages
OAuth2_Dynamics365 := TOAuth2Authenticator.Create(nil);
OAuth2_Dynamics365.TokenType := TOAuth2TokenType.ttBEARER;
RESTClient := TRESTClient.Create('https://login.microsoftonline.com/');
RESTClient.ContentType := 'application/x-www-form-urlencoded';
RESTRequest := TRESTRequest.Create(RESTClient);
RESTRequest.Method := TRESTRequestMethod.rmPOST;
// RESTRequest.Resource := '/' + ATenantID + '/oauth2/token';
RESTRequest.Resource := '/' + ATenantID + '/oauth2/v2.0/token';
// https://login.windows.net/common/oauth2/authorize?response_type=code&resource=https%3A%2F%2Fmanage.office.com&client_id={your_client_id}&redirect_uri={your_redirect_url }
RESTRequest.Params.AddItem('client_id', AClientID, TRESTRequestParameterKind.pkGETorPOST);
RESTRequest.Params.AddItem('scope', Scope, TRESTRequestParameterKind.pkGETorPOST);
RESTRequest.Params.AddItem('client_secret', AClientSecret, TRESTRequestParameterKind.pkGETorPOST);
RESTRequest.Params.AddItem('grant_type', 'client_credentials', TRESTRequestParameterKind.pkGETorPOST);
RESTRequest.Client := RESTClient;
try
RESTRequest.Execute;
if RESTRequest.Response.StatusCode = 200 then
begin
if RESTRequest.Response.GetSimpleValue('access_token', AToken) then
OAuth2_Dynamics365.AccessToken := AToken;
RESTClient.BaseURL := 'https://graph.microsoft.com';
RESTClient.Authenticator := OAuth2_Dynamics365;
RESTRequest.Params.Clear();
RESTRequest.Resource := 'v1.0/me/messages';
RESTRequest.Execute;
end;
except
on EHTTP: EHTTPProtocolException do
Memo1.Lines.Text := 'HTTP Error ' + EHTTP.Message;
on EREST: ERESTException do
Memo1.Lines.Text := 'REST Error ' + EREST.Message;
end;
Memo1.Lines.Text := RESTRequest.Response.Content; |
Partager