使用 OpenIdConnect 在 ASP.NET Core 上为移动应用程序和网站验证 REST API

Authenticated REST API for a mobile app and website on ASP.NET Core with OpenIdConnect

我有一个相当多的样板 "ASP.NET Core Web Application (.NET Framework)" 应用程序,应该成为 REST API,托管在 Azure 上,用于网站和移动应用程序。

我想通过 headers 为其配备令牌身份验证,并且我选择了 OpenIdConnect 包。

我已将此页面 (https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server) 中的片段复制粘贴到我的模板中,并添加了 app.UseOAuthValidation() 调用,因此代码如下所示:

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();
    services.AddAuthentication();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseOAuthValidation();

    app.UseOpenIdConnectServer(options =>
        {
              //..... Copy-paste from the OpenIdConnect page

              OnValidateTokenRequest = context => { ... }
              OnHandleTokenRequest = context => { ... }
        });

    app.UseMvc();
}

我可以获得令牌(POST 到 /connect/token)。

如果我将 [Authorize] 添加到我的 ValuesController 以获取并使用令牌设置授权 header 但我继续获得 401 未授权。该代码甚至没有进入 OnValidateTokenRequest 或 OnHandleTokenRequest 方法。

我错过了什么?

你做错了。

让我简单解释一下。您的 REST API 将不是 OpenIDConnect 服务器。它应该只验证给它的令牌。

这篇文章看起来不错:https://contos.io/protecting-a-net-core-api-with-azure-active-directory-59bbcd5b3429#.1w8djbaci此示例使用 Azure AD,但由于您托管在 Azure 上,我认为这对您来说是个不错的选择。

简而言之,您的 API:

中需要这样的东西
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
    Authority = Configuration[“Authentication:AzureAd:AADInstance”] 
    + Configuration[“Authentication:AzureAd:TenantId”], 
    Audience = Configuration[“Authentication:AzureAD:ClientId”], 
    TokenValidationParameters = 
    new Microsoft.IdentityModel.Tokens.TokenValidationParameters 
      {
        ValidIssuer = 
        Configuration [“Authentication:AzureAd:AADInstance”] 
      + Configuration[“Authentication:AzureAd:TenantId”] + “/v2.0” }
});