我在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
。
答案 0 :(得分:0)
httpContext.Request.Headers.TryGetValue("Authorization", out var token);