【问题标题】:Error using OpenID Connect with .NET Core 3.0 ASP.NET Core API service将 OpenID Connect 与 .NET Core 3.0 ASP.NET Core API 服务一起使用时出错
【发布时间】:2020-02-08 13:53:31
【问题描述】:

我正在尝试在 .NET Core 3.0 ASP.NET Core API 服务中使用 Azure AD 实现 OpenID Connect。

它只是一个 API 服务,没有 UI,使用单独的 SPA 来访问 API 服务。

根据 here 的说明,我从我的 SPA 发送登录请求,在身份验证后,该请求被重定向回我 API 上的 /signin-oidc 端点。

此时,我得到一个错误:-

Error from RemoteAuthentication: "Unable to unprotect the message.State.".

来自 SPA 的初始请求如下所示:-

tenantId = my Azure AD tenant ID
clientId = my Azure AD application ID
responseType = "id_token"
redirectUri = "http://localhost:12345/signin-oidc"
scope = "openid"
responseMode = "form_post"
state = "12345"
nonce = "67890"

https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/authorize?client_id={clientId}&response_type={responseType}&redirect_uri={redirectUri}&scope={scope}&response_mode={responseMode}&state={state}&nonce={nonce}

我的 API 启动代码如下所示:-

services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
    .AddAzureAD(o =>
    {
        o.ClientId = "(tenant id)";
        o.TenantId = "(client id)";
        o.Instance = "https://login.microsoftonline.com/";
    })
    .AddAzureADBearer(o =>
    {
        o.ClientId = "(tenant id)";
        o.TenantId = "(client id)";
        o.Instance = "https://login.microsoftonline.com/";
    });

如果我在初始请求中省略了 state 参数,我会得到一个不同的错误:-

Error from RemoteAuthentication: "OpenIdConnectAuthenticationHandler: message.State is null or empty.".

引用的说明说state是推荐的,不是必需的:-

请求中包含的值也将在令牌响应中返回。它可以是您想要的任何内容的字符串。随机生成的唯一值通常用于防止跨站点请求伪造攻击。状态还用于在身份验证请求发生之前对有关用户在应用中的状态信息进行编码,例如用户所在的页面或视图。

但是,我得到的错误似乎暗示state 是必需的,并且需要专门生成。

我也尝试了以下启动代码,并得到相同的错误:-

services.AddAuthentication(options =>
{
    options.DefaultScheme = Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
    .AddCookie()
    .AddOpenIdConnect(options =>
    {
        options.ClientId = "(client id)";
        options.Authority = "https://login.microsoftonline.com/" + "(tenant id)";
    });

【问题讨论】:

  • 你修好了吗?我得到相同的“来自 RemoteAuthentication 的错误:“OpenIdConnectAuthenticationHandler:message.State 为空或为空。”。

标签: asp.net-core asp.net-core-webapi openid-connect


【解决方案1】:

我认为的问题是您不能从您的 SPA 应用程序直接向 /signin-oidc 发送请求。因为 AddOpenIdConnect(...) 处理程序要求它是向 AzureAd 发出初始请求的人,并且它还需要将请求返回给 /signin-oidc。

AddOpenIdConnect 设置自己的状态值并将 is 传递给身份提供者 a,它希望稍后在浏览器调用 /signin-oidc 时看到相同的状态值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-10
    • 2016-12-18
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 2018-12-12
    相关资源
    最近更新 更多