【问题标题】:Microsoft Identity Platform in an ASP.NET Core projectASP.NET Core 项目中的 Microsoft 身份平台
【发布时间】:2021-11-18 18:55:30
【问题描述】:

我有一个使用 Microsoft 身份平台作为身份验证方法的 ASP.NET Core Web 应用程序项目。我想将 REST API 功能添加到同一个项目中,但似乎我无法将 AddMicrosoftIdentityWebApi 方法与 AddMicrosoftIdentityWebApp 一起添加。

StartUp.cs 中,我将两个AddAuthentication 调用放在一起:

Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"));
Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAd"));

编译没有错误,但是当我启动项目时,它立即返回 401 错误。我认为这是因为第二行 AddAuthentication 替换了第一行,所以我无法启动网站。

我只是想问一下,该项目是否可以使用 Microsoft Identity Platform 同时提供 Web 应用程序和 Rest API,或者我需要将其分成两个项目,一个用于 Web 应用程序,一个用于 Web API。如果是这样,我怎样才能为两个项目共享相同的数据库和模型?

非常感谢!

【问题讨论】:

标签: c# microsoft-identity-platform


【解决方案1】:

我需要保护 Web API 和 Swagger UI。我是这样做的:

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration);

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration);

builder.Services.AddSwaggerGen();

然后:

app.UseAuthentication();

app.UseAuthorization();

app.UseSwagger();

app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1");
});

app.Map("/swagger/index.html", () => "This endpoint requires authorization")
    .RequireAuthorization(new AuthorizeAttribute
    {
        AuthenticationSchemes = OpenIdConnectDefaults.AuthenticationScheme,
    });

app.MapControllers();

这会导致 Web API 需要不记名令牌,并且 Swagger UI 本身会将未经身份验证的用户重定向到 Azure AD 登录页面(然后登录)。

【讨论】:

    猜你喜欢
    • 2021-02-06
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    • 1970-01-01
    相关资源
    最近更新 更多