【发布时间】:2020-04-22 02:45:55
【问题描述】:
我有一个在 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"];
});
【问题讨论】:
标签: c# asp.net api scope identityserver4