Ale*_*eks 7 openid-connect asp.net-core asp.net-core-webapi
我正在尝试在 .NET Core 3.0 ASP.NET Core API 服务中使用 Azure AD 实现 OpenID Connect。
它只是一个 API 服务,没有 UI,并且使用单独的 SPA 来访问 API 服务。
根据此处的说明,我从我的 SPA 发送登录请求,在身份验证后,该请求被重定向回/signin-oidc我的 API 上的端点。
此时,我收到一个错误:-
Error from RemoteAuthentication: "Unable to unprotect the message.State.".
Run Code Online (Sandbox Code Playgroud)
来自 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}
Run Code Online (Sandbox Code Playgroud)
我的 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/";
});
Run Code Online (Sandbox Code Playgroud)
如果我从初始请求中省略 state 参数,我会收到一个不同的错误:-
Error from RemoteAuthentication: "OpenIdConnectAuthenticationHandler: message.State is null or empty.".
Run Code Online (Sandbox Code Playgroud)
引用的说明说这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)";
});
Run Code Online (Sandbox Code Playgroud)
我认为问题是您无法从 SPA 应用程序直接向 /signin-oidc 发送请求。因为 AddOpenIdConnect(...) 处理程序要求它是向 AzureAd 发出初始请求的处理程序,并且它也是接收返回到 /signin-oidc 的请求的处理程序。
\nAddOpenIdConnect 设置自己的状态值并将其传递给身份提供者 a,并且它希望稍后当浏览器调用 /signin-oidc 时看到相同的状态值。
\n我最近在博客中发表了有关状态和随机数参数的文章:
\n\n| 归档时间: |
|
| 查看次数: |
2528 次 |
| 最近记录: |