【发布时间】: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