客户端应用程序如何使用从访问令牌中提取的范围和资源来限制API - identityserver4的访问



我可以看到许多描述如何使用identityserver4的链接。

主机应用程序:用[clientId, secret, apiscope, APIResources, IdentityResources]配置客户端将客户端详细信息传递给identityserver4

客户端应用程序:将客户端id传递给端点以获取包含已定义客户端范围和资源的访问令牌和刷新令牌。使用这个范围和资源,我们可以限制API的访问。

但是我仍然想知道客户端应用程序将如何使用API作用域来限制应用程序的访问,是否有任何示例如何利用作用域来限制应用程序访问?

以及在identitserver4中维护角色的方法

我没有找到任何链接描述如何使用获得访问令牌后的客户端部分,请分享给我任何参考可以帮助我?

在API (AddJwtBearer)中,您做两件事,身份验证和授权。

在授权阶段,检查访问令牌中找到的声明(范围是声明的一部分)。

可以使用基于角色或策略的方法进行授权检查。

策略示例如下:

public void ConfigureServices(IServiceCollection services)
{
services.AddAuthorization(options =>
{
options.AddPolicy("ViewReports", policy =>
policy.RequireAuthenticatedUser()
.RequireRole("Finance")
.RequireRole("Management")
);                  
});

,那么你可以用这个属性来装饰你的控制器:

[Authorize("ViewReports")]
public class SecretController : Controller
{
}

从消费者(API)的角度来看,范围就像所有其他声明一样。他们没有被区别对待。

当使用identityserver4时,客户端需要配置ClientId和权限地址,此服务器需要配置与ClientId对应的允许范围

services.AddAuthentication(config=>
{
config.DefaultScheme = "cookie";
config.DefaultChallengeScheme = "oidc";
})
.AddCookie("cookie")
.AddOpenIdConnect("oidc", config=>
{
config.Authority = "url";
config.ClientId = "client_id";
config.ClientSecret = "client_secret";
config.SaveTokens = true;
config.ResponseType = "code";
});

Identityserver将根据ClientId对某些功能进行授权。

new Client
{
ClientId="client_id",
ClientSecrets=
{
new Secret("client_secret".ToSha256())
},
AllowedGrantTypes=GrantTypes.Code,
RedirectUris={ "https://localhost:[port]/signin-oidc"},
AllowedScopes={ "apione", "apitwo", 
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
//...
},
RequireConsent=false
}

在apione中,您仍然需要配置受众。

services.AddAuthentication("jwtauth")
.AddJwtBearer("jwtauth",config=>
{
config.Authority = "identityserver url";
config.Audience = "apione";
config.RequireHttpsMetadata = false;
IdentityModelEventSource.ShowPII = true;
});

每个用户都有自己的角色,因此可以在用户登录服务器后添加声明。此外,项目api可以像Tore Nestenius所说的那样配置AddAuthorization。

最新更新