Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Current »

Example of C# code how to authenticate using a webclient.

the oAuth2Url is <Hostname>/identity/connect/token

and what you get back are the follow values:

access_token: the access token required for calling the api

expires_in: how long the token last.

token_type: usually type is bearer

refresh_token: token used to reauthenticate, will be shown later.

string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(_ClientId + ":" + _ClientSecret));
string urlEncodeScope = HttpUtility.UrlEncode(_ApiScope);
string body = "grant_type=password&username=" + _UserName + "&password=" + _Password + "&scope=" + urlEncodeScope;

WebClient wbclient = new WebClient();
wbclient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
wbclient.Headers.Add("Authorization", "Basic " + credentials);
wbclient.Headers.Add("Cache-Control", "no-cache");
var wbresponse = wbclient.UploadString(oAuth2Url, body);
dynamic obj = JsonConvert.DeserializeObject<dynamic>(wbresponse);
_Token = obj.access_token;
_ExpireTime = obj.expires_in;
_TokenType = obj.token_type;
_RefreshToken = obj.refresh_token;
this._TokenRefreshTime = DateTime.UtcNow.AddMinutes((_ExpireTime));

If your token expires, you need to reauthenticate using the refresh token, the main difference is in the grant type is now reresh_token, so you dont have to send username and password multiple times

string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(_ClientId + ":" + _ClientSecret));
string body = "grant_type=refresh_token&refresh_token=" + _RefreshToken + "&client_id=" + _ClientId + "&client_secret=" + _ClientSecret;

WebClient wbclient = new WebClient();
wbclient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
wbclient.Headers.Add("Authorization", "Basic " + credentials);
wbclient.Headers.Add("Cache-Control", "no-cache");
var wbresponse = wbclient.UploadString(oAuth2Url, body);
dynamic obj = JsonConvert.DeserializeObject<dynamic>(wbresponse);
_Token = obj.access_token;
_ExpireTime = obj.expires_in;
_TokenType = obj.token_type;
_RefreshToken = obj.refresh_token;
this._TokenRefreshTime = DateTime.UtcNow.AddMinutes((_ExpireTime));
  • No labels