C# Code Sample
Dependencies
- .NET 5 SDK
- Newtonsoft.Json NuGet Package
- Nortridge.NlsWebApi.Client NuGet Package (version should match RESTful Web Services version)
Program.cs
using System.Threading.Tasks;
namespace Nortridge.NlsWebApi.Samples
{
class Program
{
static async Task Main(string[] args)
{
await RefreshTokenSample.RunAsync();
await NlsWebApiClientSample.RunAsync();
}
}
}
RefreshTokenSample.cs
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace Nortridge.NlsWebApi.Samples {
public class RefreshTokenSample {
const string AuthServerBaseAddress =
"https://[your_domain:9090/]";
const string ApiServerBaseAddress =
"https://[your_domain:8080/]";
const string ClientId = "enter_client_id";
const string ClientSecret = "enter_client_serect";
const string NlsUsername = "enter_nls_username";
const string NlsPassword = "enter_nls_password";
const string GetAccessTokenEndpoint = "/core/connect/token";
const string RevokeTokenEndpoint = "/core/connect/revocation";
const string GetVersionEndpoint = "/version";
public static async Task RunAsync() {
// Request Access Token with offline_access scope, so that a
Refresh Token is returned
var tokenResponse = await RequestAccessTokenAsync();
Console.WriteLine("Access Token: " +
tokenResponse.AccessToken);
Console.WriteLine("Refresh Token: " +
tokenResponse.RefreshToken);
// Use Access Token in REST API request
var getVersionResponse = await
GetVersionAsync(tokenResponse.AccessToken);
Console.WriteLine("Get Version Response: " +
getVersionResponse);
// if the Access Token expires, a new Access Token can be
requested without NLS User Credentials by using the Refresh Token
var refreshTokenResponse = await
RequestAccessTokenAsync(tokenResponse.RefreshToken);
Console.WriteLine("Access Token: " +
refreshTokenResponse.AccessToken);
Console.WriteLine("Refresh Token: " +
refreshTokenResponse.RefreshToken);
// Access Tokens and Refresh Tokens can be revoked
var tokenRevoked = await
RevokeTokenAsync(tokenResponse.AccessToken, "access_token");
if (tokenRevoked) {
Console.WriteLine("Access Token Revoked: " +
tokenResponse.AccessToken);
}
tokenRevoked = await
RevokeTokenAsync(tokenResponse.RefreshToken, "refresh_token");
if (tokenRevoked) {
Console.WriteLine("Refresh Token Revoked: " +
tokenResponse.RefreshToken);
}
tokenRevoked = await
RevokeTokenAsync(refreshTokenResponse.AccessToken, "access_token");
if (tokenRevoked) {
Console.WriteLine("Access Token Revoked: " +
refreshTokenResponse.AccessToken);
}
tokenRevoked = await
RevokeTokenAsync(refreshTokenResponse.RefreshToken, "refresh_token");
if (tokenRevoked) {
Console.WriteLine("Refresh Token Revoked: " +
refreshTokenResponse.RefreshToken);
}
Console.ReadLine();
}
private static async Task < TokenResponse > RequestAccessTokenAsync() {
using(var client = new HttpClient()) {
var parameters = new Dictionary < string,
string > {
{
"grant_type",
"password"
},
{
"scope",
"api openid offline_access"
},
{
"username",
NlsUsername
},
{
"password",
NlsPassword
},
{
"client_id",
ClientId
},
{
"client_secret",
ClientSecret
},
};
client.BaseAddress = new Uri(AuthServerBaseAddress);
HttpResponseMessage response = await
client.PostAsync(GetAccessTokenEndpoint, new FormUrlEncodedContent(parameters));
var jsonResponse = await
response.Content.ReadAsStringAsync();
var tokenResponse =
JsonConvert.DeserializeObject < TokenResponse > (jsonResponse);
return tokenResponse;
}
}
private static async Task < TokenResponse >
RequestAccessTokenAsync(string refreshToken) {
using(var client = new HttpClient()) {
var parameters = new Dictionary < string,
string > {
{
"grant_type",
"refresh_token"
},
{
"refresh_token",
refreshToken
},
{
"client_id",
ClientId
},
{
"client_secret",
ClientSecret
},
};
client.BaseAddress = new Uri(AuthServerBaseAddress);
HttpResponseMessage response = await
client.PostAsync(GetAccessTokenEndpoint, new FormUrlEncodedContent(parameters));
var jsonResponse = await
response.Content.ReadAsStringAsync();
var tokenResponse =
JsonConvert.DeserializeObject < TokenResponse > (jsonResponse);
return tokenResponse;
}
}
private static async Task < string > GetVersionAsync(string accessToken) {
using(var client = new HttpClient()) {
client.DefaultRequestHeaders.Authorization = new
AuthenticationHeaderValue("Bearer", accessToken);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.BaseAddress = new Uri(ApiServerBaseAddress);
HttpResponseMessage response = await
client.GetAsync(GetVersionEndpoint);
var jsonResponse = await
response.Content.ReadAsStringAsync();
return jsonResponse;
}
}
private static async Task < bool > RevokeTokenAsync(string token,
string token_type_hint) {
using(var client = new HttpClient()) {
var parameters = new Dictionary < string,
string > {
{
"token",
token
},
{
"token_type_hint",
token_type_hint
}
};
var authenticationString = $ "{ClientId}:{ClientSecret}";
var base64EncodedAuthenticationString =
Convert.ToBase64String(Encoding.UTF8.GetBytes(authenticationString));
client.DefaultRequestHeaders.Add("Authorization", "Basic " +
base64EncodedAuthenticationString);
client.BaseAddress = new Uri(AuthServerBaseAddress);
HttpResponseMessage response = await
client.PostAsync(RevokeTokenEndpoint, new FormUrlEncodedContent(parameters));
return response.IsSuccessStatusCode;
}
}
private class TokenResponse {
[JsonProperty("access_token")]
public string AccessToken {
get;
set;
}
[JsonProperty("expires_in")]
public int ExpiresIn {
get;
set;
}
[JsonProperty("token_type")]
public string TokenType {
get;
set;
}
[JsonProperty("refresh_token")]
public string RefreshToken {
get;
set;
}
[JsonProperty("id_token")]
public string IdToken {
get;
set;
}
}
}
}
NlsWebApiClientSample.cs
using Newtonsoft.Json;
using Nortridge.NlsWebApi.Client;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace Nortridge.NlsWebApi.Samples {
public class NlsWebApiClientSample {
const string AuthServerBaseAddress =
"https://[your_domain:9090/]";
const string ApiServerBaseAddress =
"https://[your_domain:8080/]";
const string ClientId = "enter_client_id";
const string ClientSecret = "enter_client_secret";
const string NlsUsername = "enter_nls_username";
const string NlsPassword = "enter_nls_password";
const string GetAccessTokenEndpoint = "/core/connect/token";
const string RevokeTokenEndpoint = "/core/connect/revocation";
public static async Task RunAsync() {
var tokenResponse = await RequestAccessTokenAsync();
Console.WriteLine("Access Token: " +
tokenResponse.AccessToken);
using(var httpClient = new HttpClient()) {
httpClient.BaseAddress = new Uri(ApiServerBaseAddress);
httpClient.DefaultRequestHeaders.Authorization = new
AuthenticationHeaderValue("Bearer", tokenResponse.AccessToken);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var nlsWebApiClient = new NlsWebApiClient(httpClient);
var getContactResponse = await
nlsWebApiClient.Contacts_GetAsync(1);
Console.Write("Get Contact Response:" +
getContactResponse.ToJson());
Console.WriteLine("Contact Cifnumber:" +
getContactResponse.Payload.Data.Cifnumber);
}
var tokenRevoked = await
RevokeTokenAsync(tokenResponse.AccessToken, "access_token");
if (tokenRevoked) {
Console.WriteLine("Access Token Revoked: " +
tokenResponse.AccessToken);
}
Console.ReadLine();
}
private static async Task < TokenResponse > RequestAccessTokenAsync() {
using(var client = new HttpClient()) {
var parameters = new Dictionary < string,
string > {
{
"grant_type",
"password"
},
{
"scope",
"api openid"
},
{
"username",
NlsUsername
},
{
"password",
NlsPassword
},
{
"client_id",
ClientId
},
{
"client_secret",
ClientSecret
},
};
client.BaseAddress = new Uri(AuthServerBaseAddress);
HttpResponseMessage response = await
client.PostAsync(GetAccessTokenEndpoint, new FormUrlEncodedContent(parameters));
var jsonResponse = await
response.Content.ReadAsStringAsync();
var tokenResponse =
JsonConvert.DeserializeObject < TokenResponse > (jsonResponse);
return tokenResponse;
}
}
private static async Task < bool > RevokeTokenAsync(string token,
string token_type_hint) {
using(var client = new HttpClient()) {
var parameters = new Dictionary < string,
string > {
{
"token",
token
},
{
"token_type_hint",
token_type_hint
}
};
var authenticationString = $ "{ClientId}:{ClientSecret}";
var base64EncodedAuthenticationString =
Convert.ToBase64String(Encoding.UTF8.GetBytes(authenticationString));
client.DefaultRequestHeaders.Add("Authorization", "Basic " +
base64EncodedAuthenticationString);
client.BaseAddress = new Uri(AuthServerBaseAddress);
HttpResponseMessage response = await
client.PostAsync(RevokeTokenEndpoint, new FormUrlEncodedContent(parameters));
return response.IsSuccessStatusCode;
}
}
private class TokenResponse {
[JsonProperty("access_token")]
public string AccessToken {
get;
set;
}
[JsonProperty("expires_in")]
public int ExpiresIn {
get;
set;
}
[JsonProperty("token_type")]
public string TokenType {
get;
set;
}
[JsonProperty("refresh_token")]
public string RefreshToken {
get;
set;
}
[JsonProperty("id_token")]
public string IdToken {
get;
set;
}
}
}
}
Updated almost 3 years ago