The following code snippet shows how to get an OAuth token in C#, where the user gets prompted to login through the Azure Active Directory Sign-on page if a token isn't found.
Copy
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
Uri _baseUrl = new Uri("https://[environmentid]/api"); //TODO: replace with your K2 environment's URL
string _clientId = "3cb1141a-a226-497d-a512-8a4a2e512aec"; //Application ID of the client requesting the token (K2 API app, in this case)
string _authority = "https://login.microsoftonline.com/common/login"; //Login URL for <span class="mc-variable BrandingThirdParty.Azure_Active_Directory variable">Azure Active Directory</span> Instance
string _redirectUri = @"https://api.k2.com/client"; //Address to return to upon receiving a response from the authority
string _webApiResourceId = @"https://api.k2.com/"; //Identifier of the target resource that is the recipient of the requested token
string _resource = "/odata/v3/"; //the endpoint you want to query (in this case, all SmartObjects that have at least one list method are returned)
//string _resource = "/odatav4/v4/"; // this is the OData v4 endpoint
//set up http client
System.Net.Http.HttpClient _httpClient = new HttpClient(new HttpClientHandler()
{
UseDefaultCredentials = false,
});
//platform specific arguments and information
Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters parameters = new PlatformParameters(PromptBehavior.Auto);
//retrieves authentication tokens from <span class="mc-variable BrandingThirdParty.Azure_Active_Directory variable">Azure Active Directory</span> and ADFS services
Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext authContext = new AuthenticationContext(_authority);
Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult authResult = null;
try {
//get the OAuth token (will show login screen to user if no token found)
authResult = authContext.AcquireTokenAsync(_webApiResourceId, _clientId, new Uri(_redirectUri), parameters).Result;
} catch (Microsoft.IdentityModel.Clients.ActiveDirectory.AdalException adalEx) {
//TODO: do something with the auth error
return;
}
//use pathos client to construct the HTTP request and read response
Pathoschild.Http.Client.IRequest request = null;
Pathoschild.Http.Client.IResponse result = null;
request = (Pathoschild.Http.Client.IRequest) new Pathoschild.Http.Client.FluentClient(_baseUrl, _httpClient).GetAsync(_resource).WithHttpErrorAsException(false);
//pass in the access token that was obtained
request = request.WithBearerAuthentication(authResult.AccessToken);
result = request.AsResponse().Result;
//get the result form the endpoint call
string returnvalue = result.Message.Content.ReadAsStringAsync().Result;