Request Information
Example:
using IdentityModel;
using IdentityModel.Client;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Net.Http;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace Demo
{
internal class Program
{
// Install-Package IdentityModel
// Install-Package System.IdentityModel.Tokens.Jwt
static string clientId = "****************";
static string identityUrl = "https://identity-public.********.com";
static string apiUrl = "https://graph-public.*************.com/dynamicsbackup";
static async Task Main(string[] args)
{
var client = new HttpClient();
var disco = await client.GetDiscoveryDocumentAsync(identityUrl);
if (disco.IsError)
{
Console.WriteLine(disco.Error);
return;
}
var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
{
Address = disco.TokenEndpoint,
ClientAssertion = new ClientAssertion()
{
Type = OidcConstants.ClientAssertionTypes.JwtBearer,
Value = CreateClientAuthJwt(disco)
},
Scope = "dynamics.readwrite.all",
});
if (tokenResponse.IsError)
{
Console.WriteLine(tokenResponse.Error);
return;
}
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + tokenResponse.AccessToken);
string filter = JsonConvert.SerializeObject(new
{
pageInfo = new
{
currentPage = 1,
pageSize = 5,
},
startTime = 1385587340740,
endTime = 1785587340740,
type = 1,
status = 3,
organizationId = "5c47faf1-8d22-43df-9140-b200174fe0e7",
objectType = 1
});
HttpContent content = new StringContent(filter, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(apiUrl + "/api/Job/GetJobs", content);
string result = await response.Content.ReadAsStringAsync();
// You can continue configuring to export the response information to CSV or Excel file.
// ...
}
private static string CreateClientAuthJwt(DiscoveryDocumentResponse response)
{
// set exp to 5 minutes
var tokenHandler = new JwtSecurityTokenHandler { TokenLifetimeInMinutes = 5 };
var securityToken = tokenHandler.CreateJwtSecurityToken(
// iss must be the client_id of our application
issuer: clientId,
// aud must be the identity provider (token endpoint)
audience: response.TokenEndpoint,
// sub must be the client_id of our application
subject: new ClaimsIdentity(
new List<Claim> { new Claim("sub", clientId),
new Claim("jti", Guid.NewGuid().ToString())}),
// sign with the private key (using RS256 for IdentityServer)
signingCredentials: new SigningCredentials(
new X509SecurityKey(new X509Certificate2(LoadCertificate())), "RS256")
);
return tokenHandler.WriteToken(securityToken);
}
private static X509Certificate2 LoadCertificate()
{
string fileName = Path.Combine(AppContext.BaseDirectory, "dynamics.pfx");
string password = "******";
return new X509Certificate2(fileName, password);
}
}
}