我正在编写 ASP.Net Core 2.0 Web 应用程序,并尝试使用 Azure AD B2C 进行身份验证。
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<SchoolContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.Authority = "https://login.microsoftonline.com";
options.Audience = "aud";
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = t =>
{
return Task.FromResult(0);
}
};
})
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
options.MetadataAddress = $"https://login.microsoftonline.com/{Configuration["AzureAdB2C:Tenant"]}/v2.0/.well-known/openid-configuration?p={Configuration["AzureAdB2C:Policy"]}";
options.ClientId = Configuration["AzureAdB2C:ClientId"];
options.Events = new OpenIdConnectEvents { OnAuthenticationFailed = AuthenticationFailed, OnTokenValidated = Validated, OnRemoteFailure = Failed };
options.SaveTokens = true;
});
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
}));
services.AddMvc();
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new CorsAuthorizationFilterFactory("MyPolicy"));
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication();
if (env.IsDevelopment())
{
var builder = new ConfigurationBuilder();
builder.AddUserSecrets<Startup>();
app.UseDeveloperExceptionPage();
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
HotModuleReplacement = true,
ReactHotModuleReplacement = true
});
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseCors("MyPolicy");
app.UseMvc();
}
我在 Controller 操作上有一个 [Authorize]
属性,当我点击该链接时,我会看到 Microsoft 登录页面。我成功登录,它将我重定向回 https://localhost:[PORT]/signin-oidc
,它返回 500 服务器错误。
我的问题是有人知道为什么会发生这种情况吗?我认为这可能与 CORS 有关,但看起来并非如此。来自 Microsoft 的帖子似乎包含有效的 token 。
最佳答案
Visual Studio 调试窗口通常包含一些有用的信息来帮助排除故障。
<小时/>我会更改您的启动代码以匹配 this sample (删除对 AddOpenIdConnect()
的调用):
services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(jwtOptions =>
{
jwtOptions.Authority = $"https://login.microsoftonline.com/tfp/{Configuration["AzureAdB2C:Tenant"]}/{Configuration["AzureAdB2C:Policy"]}/v2.0/";
jwtOptions.Audience = Configuration["AzureAdB2C:ClientId"];
jwtOptions.Events = new JwtBearerEvents
{
OnAuthenticationFailed = AuthenticationFailed
};
});
<小时/>
我还会向 JwtBearerEvents
中的 OnMessageReceived
添加一个处理程序。在该处理程序上放置一个断点,看看是否能做到这一点。
关于azure - Azure AD B2C 调用signin-oidc 回调时出现 500 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47777455/