Active Directory Authorisation Tokens in C#
Post by: syed hussain in All C# Tips
Summary
Here is a quick tip for anyone trying to get an OAuth2 JWT token from an Azure AD 2.0 endpoint.
https://login.microsoftonline.com/common/oauth2/v2.0/token
Request a JWT Token
Three pieces of information are required:
- client_id (obtained from the app registration).
- client_secret (obtained from the app registration).
- scope (defaulted to all scoped below)
public async Task GetTokenAsync()
{
var client = new RestClient("https://login.microsoftonline.com/common/oauth2/v2.0/token");
var request = new RestRequest($"", Method.Get);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Cookie", "fpc=AoYuco9kc5dGkrf4E9KZpcJLV8dmAQAAABL3DtoOAAAA; stsservicecookie=estsfd; x-ms-gateway-slice=estsfd");
request.AddParameter("grant_type", "client_credentials");
request.AddParameter("client_id", "3000000-9b2d-488f-b587-8be16d300595");
request.AddParameter("client_secret", "XAAAAA-_ZvALLEze6FYf2LbVACffjJ8q~i2Mar.");
request.AddParameter("scope", "https://diskussio.onmicrosoft.com/3657a273-3560-0000-a647-b949ead0d43c/.default");
var response = await client.PostAsync<TokenResponse>(request);
}
record TokenResponse
{
[JsonPropertyName("token_type")]
public string? TokenType { get; init; }
[JsonPropertyName("access_token")]
public string? AccessToken { get; init; }
}
The response will now contain the bearer token.