我有 2 个项目,一个用于 API,第二个用于使用第一个项目的 API 查看和获取数据。对于这两者,我已经实现了 Azure AD 身份验证,但我的问题是当尝试使用 Bearer 令牌从第二个项目后端(C#)调用 API 但作为响应我得到以下错误。
注意:我在每个类和两个项目中的方法中都使用了 [Authorize] 过滤器。
错误
AuthenticationFailed:IDX10501:签名验证失败。无法匹配 'kid':'SSQdhI1cKvhQEDSJxE2gGYs40Q0',令牌:'{"alg":"RS256","typ":"JWT","kid":"SSQdhI1cKvhQEDSJxE2gGYs40Q0"}。{"aud":"1e615ddb-ad4d- 4e65-98de-c6f5db1ae08a","iss":" https://login.microsoftonline.com/5c58f0d9-2f98-4eb0-91f2-ec6afd4242f8/v2.0 ","iat":1518520450,"nbf":1518520450," exp":1518524350,"aio":"Y2NgYHiknfZAIvPElucJpgeZzRa5AAA=","azp":"1e615ddb-ad4d-4e65-98de-c6f5db1ae08a","azpacr":"1","e_exp":262800,"oid":"159f0ec6 -c5b9-4bfc-88d0-77924bd40b3f","sub":"
启动类 ConfigureServices 方法
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddAzureAdB2C(options => Configuration.Bind("Authentication:AzureAdB2C", options))
.AddCookie();
// Add framework services.
services.AddMvc();
// Adds a default in-memory implementation of IDistributedCache.
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromHours(1);
options.CookieHttpOnly = true;
});
}
启动类配置方法
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseSession();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
获取 Bearer Token 的类
public class ServicePrincipal
{
static string authority = "https://login.microsoftonline.com/{TenantID}/{Policy}/v2.0/";
static string clientId = "XXX";
static string clientSecret = "XXX";
static string resource = "XXX";
static public async Task<Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult> GetS2SAccessTokenForProdMSAAsync()
{
return await GetS2SAccessToken(authority, resource, clientId, clientSecret);
}
static async Task<Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult> GetS2SAccessToken(string authority, string resource, string clientId, string clientSecret)
{
var clientCredential = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(clientId, clientSecret);
AuthenticationContext context = new AuthenticationContext(authority, false);
Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult authenticationResult = await context.AcquireTokenAsync(resource,clientCredential);
return authenticationResult;
}
}
我试图调用第一个项目的 API 的控制器方法
public async Task<IActionResult> GetCustomerGroupAsync()
{
try
{
var token = await ServicePrincipal.GetS2SAccessTokenForProdMSAAsync();
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
HttpResponseMessage response = await _client.GetAsync("http://localhost:49942/api/customermodule/v0.3/customergroup");
response.EnsureSuccessStatusCode();
string receiveStream = await response.Content.ReadAsStringAsync();
return null;
}
catch (Exception e)
{
return Json(new { Error = e.Message });
}
}
如果我遗漏了什么或者我做错了什么,请告诉我?谢谢。