简体   繁体   中英

Acquire Azure token from .Net Core 2.0 controller (Bearer)

This is my startup.cs code

services.AddAuthentication(sharedOptions =>
{
    sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddAzureAdBearer(configureOptions =>
{
    configureOptions.Instance = Environment.GetEnvironmentVariable("AD_Instance");
    configureOptions.Domain = Environment.GetEnvironmentVariable("AD_Domain");
    configureOptions.TenantId = Environment.GetEnvironmentVariable("AD_TenantId");
    configureOptions.ClientId = Environment.GetEnvironmentVariable("AD_ClientId");
}

JwtBearerDefaults.AuthenticationScheme is Bearer

These are my options:

public void Configure(string name, JwtBearerOptions options)
{
    options.Audience = _azureOptions.ClientId;
    options.Authority = $"{_azureOptions.Instance}{_azureOptions.TenantId}";
    options.TokenValidationParameters = new TokenValidationParameters()
    {
        ValidateIssuer = false
    };
    options.SaveToken = true;
}

Now, according to many blogs and Questions & Answers here I use this code to retrieve the token: (Btw application works fine more than 6 months already, don't consider some set up issues)

var token = _httpContextAccessor.HttpContext.GetTokenAsync("access_token");

And this is what it returns:

点击查看图片

What I need is the access_token. ex. Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1...

UPDATE: After I saw the comments/answers I added await, but I get null as a result.

The method GetTokenAsync("access_token") is asynchronous and is returning an System.Threading.Tasks.Task<string> result. So the var here is translating to:

Task<string> token = _httpContextAccessor.HttpContext.GetTokenAsync("access_token");

In order to access the actual result, you need to unpack it from the Task. The easiest way to do this is to use the await keyword:

string token = await _httpContextAccessor.HttpContext.GetTokenAsync("access_token");

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