Last active
November 14, 2019 12:08
-
-
Save oleksabor/a4c873e078f74086ddda57b6b29f2c74 to your computer and use it in GitHub Desktop.
how to request the Azure token using IdentityClient
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using IdentityModel.Client; | |
using Microsoft.Extensions.Options; | |
using System; | |
using System.Collections.Generic; | |
using System.Net.Http; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace Transport | |
{ | |
// from the IdentityServer4.Samples\Quickstarts\1_ClientCredentials\src\Client\ | |
public class TokenProvider | |
{ | |
static readonly ILog Log = LogProvider.GetCurrentClassLogger(); | |
private readonly IOptions<OAuthConfig> config; | |
public TokenProvider(IOptions<OAuthConfig> config) | |
{ | |
this.config = config; | |
} | |
public async Task<string> GetAsync() | |
{ | |
//https://github.com/AzureAD/microsoft-authentication-library-for-js/issues/560 | |
var config = this.config.Value; | |
Log.TraceFormat("loading token from {0} for {1}", config.GetAuthority(), config.Resource); | |
using (var client = new HttpClient()) | |
{ | |
// discover endpoints from metadata | |
var ddr = new DiscoveryDocumentRequest | |
{ | |
Address = config.GetAuthority(), | |
Policy = new DiscoveryPolicy { ValidateEndpoints = false } // login.microsoftonline.com provides invalid oauth2 endpoint | |
}; | |
var disco = await client.GetDiscoveryDocumentAsync(ddr); | |
if (disco.IsError) | |
throw new ApplicationException($"disco error:{disco.Error}, code:{disco.ErrorType}"); | |
var tr = await GetAsync(disco.TokenEndpoint, config.ClientId, config.Secret, config.GetScope()); | |
return tr.AccessToken; | |
} | |
} | |
public async Task<TokenResponse> GetAsync (string tokenEndpoint, string client, string secret, string scope) | |
{ | |
using (var http = new HttpClient()) | |
{ | |
//request token | |
var tokenResponse = await http.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest | |
{ | |
Address = tokenEndpoint, | |
ClientId = client, | |
ClientSecret = secret, | |
GrantType = "client_credentials", | |
Scope = scope, | |
}); | |
if (tokenResponse.IsError) | |
throw new ApplicationException($"token eror:{tokenResponse.Error}, descr:{tokenResponse.ErrorDescription}"); | |
return tokenResponse; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment