无法获得' access_token'来自httpcontext asp.net core

时间:2018-05-15 09:19:22

标签: c# asp.net .net-core jwt adal

我在Asp.Net Core 2.0项目中从httpContext获取令牌时遇到问题。我在前面部分有隐式ADAL授权,我在获取令牌时会在访问我的API时将其发送到标头中。身份验证进展顺利,但当我想获取Microsoft Graph API请求的令牌时,我获得了null

我的Startup身份验证部分:

services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(options =>
        {
            AuthenticationOptions authSettings = Configuration.GetSection("Authentication").Get<AuthenticationOptions>();
            options.TokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuer = false,
                ValidAudiences = new List<string> { authSettings.ClientId, authSettings.AppIdUri }
            };
            options.Authority = "https://login.microsoftonline.com/common";
            options.Audience = "**";
            options.TokenValidationParameters.ValidateLifetime = true;
            options.TokenValidationParameters.ClockSkew = TimeSpan.Zero;

            options.SaveToken = true;
        });

        services.AddAuthorization();

        services.AddMvc();

我需要获取令牌的方法:

public async Task AuthenticateRequestAsync(HttpRequestMessage request)
    {
        var httpContext = _httpContextAccessor.HttpContext;

        //Get the access token used to call this API
        string token = await httpContext.GetTokenAsync("access_token");

        //We are passing an *assertion* to Azure AD about the current user
        //Here we specify that assertion's type, that is a JWT Bearer token
        string assertionType = "urn:ietf:params:oauth:grant-type:jwt-bearer";

        //User name is needed here only for ADAL, it is not passed to AAD
        //ADAL uses it to find a token in the cache if available
        var user = httpContext.User;
        string userName = user.FindFirstValue(ClaimTypes.Upn) ?? user.FindFirstValue(ClaimTypes.Email);

        var userAssertion = new UserAssertion(token, assertionType, userName);

        //Construct the token cache
        var cache = new DistributedTokenCache(user, _distributedCache, _loggerFactory, _dataProtectionProvider);

        var authContext = new AuthenticationContext(_authSettings.Authority, cache);
        var clientCredential = new ClientCredential(_authSettings.ClientId, _authSettings.ClientSecret);
        //Acquire access token
        var result = await authContext.AcquireTokenAsync("https://graph.microsoft.com", clientCredential, userAssertion);
        //Set the authentication header
        request.Headers.Authorization = new AuthenticationHeaderValue(result.AccessTokenType, result.AccessToken);
    }

await httpContext.GetTokenAsync("access_token");部分null

1 个答案:

答案 0 :(得分:0)

为了令人不安,解决方案非常简单。请注意。

httpContext.Request.Headers.TryGetValue("Authorization", out var token);