c# - IdentityServer OpenIdConnect 添加一个 api 作为范围
问题描述
我有一个在 localhost:44387 上运行的项目,它是 IdentityServer 配置。我有一个在 localhost:44373 上运行的 ASP.NET Core 应用程序,它充当用户参与的前端应用程序,另一个在 localhost:44353 上运行的 ASP.NET Core 应用程序充当 API。
当用户尝试访问前端应用程序中的授权控制器时,他们将被重定向到 IdentityServer 上的登录页面。一旦用户登录,他们就会被重定向回来。
然后它们在前端应用程序上被授权,但是当调用 localhost:44353 上的 API 时,它返回未授权。
我尝试向 .OpenIdConnect 方法添加范围以将 API 添加为范围,但在重定向到登录页面时会导致应用程序崩溃。
如何将 API 添加为请求权限,以便前端应用程序获得授权后,它可以调用 API?
这在 IdentityServer 的 Config.cs 文件中
new Client
{
ClientId = "mvc",
ClientName = "MVC Client",
AllowedGrantTypes = GrantTypes.Implicit,
// where to redirect to after login
RedirectUris = { "https://localhost:44373/signin-oidc" },
// where to redirect to after logout
PostLogoutRedirectUris = { "https://localhost:44373/signout-callback-oidc" },
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"roles",
"staff_api" // <---- Add staff api as scope
},
RequireConsent = false,
}
在前端应用程序的启动内部
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = "oidc";
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
.AddOpenIdConnect("oidc", options =>
{
options.Authority = baseAuthAddress;
options.RequireHttpsMetadata = false;
options.ClientId = "mvc";
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
//options.Scope.Add("staff_api"); <--- THIS MAKES IT CRASH?
options.Scope.Add("roles");
// Fix for getting roles claims correctly :
options.ClaimActions.MapJsonKey("role", "role", "role");
options.TokenValidationParameters.NameClaimType = "name";
options.TokenValidationParameters.RoleClaimType = "roles";
});
API 的 Startup.cs 内部
services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Audience = "staff_api"; ;
options.Authority = Configuration["AuthURL"];
});
解决方案
您是否在 IdentityServer 端添加和播种ApiResource
and ?ApiScope
(使用较新版本的 IdentityServer)
如快速入门中所示?因为我们看不到完整的 Config.cs 文件,所以首先要检查。您还应该查看.well-known/openid-configuration
您的 IS4,以查看 api 的范围是否已在该部分中注册scopes_supported
(也请参见快速入门链接)。
IdentityServerTokenValidationMiddleware
在 API 端和AuthenticationMiddleware
客户端的 Debug 输出非常冗长,您应该检查调试输出中的条目,这些条目会告诉您什么不工作。
此外,GrantTypes.Implicit
如果它不是 SPA,则不应用于 Asp.Net Core 应用程序,这种类型适用于基于 JS 的前端。
推荐阅读
- javascript - (奇怪的)JavaScript 执行顺序
- javascript - 使用带有 JavaScript / Fetch 的 SpreadShirt REST API
- javascript - findByIdAndUpdate 从等于特定值的数组对象中提取
- powershell - PowerShell - 如何停止脚本处理 Timer 类中的已用事件
- laravel - 如何在 Laravel 中编写任务调度的输出?
- javascript - 使用javascript的速度计算器不起作用
- reactjs - 我该怎么做 shape.preventDefault(true); 在反应康瓦
- assembly - 为什么启用分页后特定地址不可用?
- android - 如何通过单击按钮使新捕获的图像立即获得水印
- css - 如何使用 chart.js(react-chartjs-2) 实现类似此图像的效果?