简体   繁体   中英

Configure JWT Access Token in .NET core 2 MVC application

I was successful in retrieving an Authorization token from Azure Active Directory in a console application. I want to convert this code to .Net Core MVC but not sure how to configure everything cleanly in Startup.cs

I assume the key/value pairs would be moved to appsettings.json, but how do I get this token under ConfigureServices() ?

    var client = new HttpClient();

    var uri = "https://login.microsoftonline.com/<tenantid>/oauth2/token";

    var pairs = new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("resource", "{resourceID}"),
        new KeyValuePair<string, string>("client_id", "{clientID}"),
        new KeyValuePair<string, string>("client_secret", "{clientSecret}"),
        new KeyValuePair<string, string>("grant_type", "client_credentials"),
        new KeyValuePair<string, string>("scope", "openid")
     };

    var content = new FormUrlEncodedContent(pairs);
    var response = client.PostAsync(uri, content).Result;

    string result = string.Empty;

    if (response.IsSuccessStatusCode)
    {
        result = response.Content.ReadAsStringAsync().Result;
        JObject jObject = JObject.Parse(result);
        string token = (string)jObject.SelectToken("access_token");
    }

Should I use one of the below methods to obtain the bearer token? I'm doing a POST in the console application, but that doesn't seem right for Startup configuration.

services.AddAuthentication() 

or

.AddJwtBearer()

I got it to run and authenticate, but it doesn't provide an authentication token.

As Jean said, you could use Microsoft Authentication Library (MSAL) which is the library that helps you to develop applications that work with v2.0 endpoint and here you could use it to get access token.

The scope here is the resource you want affixed with .default . Refer to this article .

The value passed for the scope parameter in this request should be the resource identifier (Application ID URI) of the resource you want, affixed with the .default suffix. For the Microsoft Graph example, the value is https://graph.microsoft.com/.default . This value informs the v2.0 endpoint that of all the direct application permissions you have configured for your app, it should issue a token for the ones associated with the resource you want to use.

The following is the C# MSAL sample code, which gets the access token for this application permission's scenario.You need to install the NuGet package Microsoft.Identity.Client in your project.

ConfidentialClientApplication app = new ConfidentialClientApplication("clientId",
    "https://login.microsoftonline.com/tenantId/v2.0",
    "redirectUrl",
    new ClientCredential("clientSecret"),
    new TokenCache(),null);
AuthenticationResult authResult = app.AcquireTokenForClientAsync(
    new string[] { "https://graph.microsoft.com/.default"}).Result;
var token = authResult.AccessToken;

Here you could change Microsoft Graph API to your API Application ID URI and for more details about adding permission and so on, you could refer to this article .

You could use an OWIN startup class instead. Refer this sample from Microsoft

https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-v1-aspnet-webapp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM