How to request a token¶
This section describes how to obtain an token from Authentication server using Client Credentials flow from any c#
application.
Requirements¶
Software requirements¶
- Framework netstandard2.0 or net461
- IdentityModel NuGet package.
Security configuration requirements¶
It's necessary to now Security configuration values:
- AuthenticationServerUrl: URL address of Authentication server (including VirtualPath).
- ClientId: The client identifier that we're going to use to ask for the token.
- ClientSecret: Secret of the client in plain text.
- Scope: Scope or scopes the need about we need the token.
Code Example¶
Next code gets an Access Token using Client Credentials flow
using IdentityModel.Client;
using System;
using System.Net.Http;
namespace TokenProvider
{
class Program
{
static async System.Threading.Tasks.Task Main(string[] args)
{
var authenticationServerUrl = "https://security.sequel.com/Authentication";
var tokenEndpoint = $"{authenticationServerUrl}/connect/token";
var clientId = "app.client";
var clientSecret = "PasswordInPlainText";
var scope = "app.scope1 app.scope2";
var client = new HttpClient();
// Request token using client credentials flow
var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
{
Address = tokenEndpoint,
ClientId = clientId,
ClientSecret = clientSecret,
Scope = scope
});
if(tokenResponse.IsError)
Console.Error.WriteLine(tokenResponse.Error);
else
Console.WriteLine(tokenResponse.AccessToken);
}
}
}
Performance improvement¶
All token's have a lifetime and we can take advantage of it reusing the token. It's possible to know directly the token's lifetime in seconds checking the tokenResponse.ExpiresIn
property. It's recommended use this value to store the token until its expiration, reducing the requests to Authentication server and, this way, increasing the performance.