【发布时间】:2020-08-09 03:54:36
【问题描述】:
我正在尝试保护我的 API 并确保我的 WebApp 只有在具有正确令牌的情况下才能访问它。
我按照教程设置了一个 nodejs,它工作正常,现在我正在尝试将相同的设置应用于 Dotnet Core 3.1 Web Api I,但是 dotnet core 的教程太可怕了。我已经浏览了几个例子,但没有什么能接近。
我的 Startup.cs 中有当前设置
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.Authority = Configuration["AzureAdB2C:Authority"];
options.Audience = Configuration["AzureAdB2C:Audience"];
});
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
在我的 appsettings.json 中
"AzureAdB2C": {
"Audience": "c6exxx-xxxxxxxx",
"Authority": "https://XXX.b2clogin.com/XX.onmicrosoft.com/B2C_SUSI_POLICY/v2.0/.well-known/openid-configuration/"
}
然而,当我从我的 WebApp(这是一个 SPA)调用时,总是得到 401。
headers: Object { normalizedNames: Map(0), lazyUpdate: null, headers: Map(0) }
message: "Http failure response for http://localhost:5000/hello: 401 Unauthorized"
name: "HttpErrorResponse"
ok: false
status: 401
statusText: "Unauthorized"
url: "http://localhost:5000/hello"
再次与此处的 nodejs 示例相同的信息 (https://docs.microsoft.com/en-us/azure/active-directory-b2c/tutorial-single-page-app-webapi?tabs=app-reg-ga) 刚刚移植到 Dotnetcore 3.1 webapi。
【问题讨论】: