5.11. 策略评估 API


使用 JavaScript 编写基于规则的策略时,红帽构建的 Keycloak 提供了一个评估 API,它提供有用的信息来帮助确定是否应授予权限。

此 API 由几个接口组成,供您访问信息,例如

  • 评估的权限,同时代表所请求的资源和范围。
  • 与请求的资源关联的属性
  • 运行时环境以及与执行上下文关联的任何其他属性
  • 有关组成员资格和角色等用户的信息

主接口是 org.keycloak.authorization.policy.evaluation.Evaluation,它定义了以下合同:

public interface Evaluation {

    /**
     * Returns the {@link ResourcePermission} to be evaluated.
     *
     * @return the permission to be evaluated
     */
    ResourcePermission getPermission();

    /**
     * Returns the {@link EvaluationContext}. Which provides access to the whole evaluation runtime context.
     *
     * @return the evaluation context
     */
    EvaluationContext getContext();

    /**
     * Returns a {@link Realm} that can be used by policies to query information.
     *
     * @return a {@link Realm} instance
     */
    Realm getRealm();

    /**
     * Grants the requested permission to the caller.
     */
    void grant();

    /**
     * Denies the requested permission.
     */
    void deny();
}

在处理授权请求时,红帽构建的 Keycloak 会在 评估 任何策略前创建一个评估实例。然后,此实例传递到每个策略,以确定访问是 GRANT 还是 DENY

通过对 评估 实例调用 grant ()deny () 方法来确定策略。默认情况下,评估 实例的状态被拒绝,这意味着您的策略必须明确调用 grant () 方法,以指示应授予的策略评估引擎。

其他资源

5.11.1. 评估上下文

评估上下文在评估期间为策略提供有用的信息。

public interface EvaluationContext {

    /**
     * Returns the {@link Identity} that represents an entity (person or non-person) to which the permissions must be granted, or not.
     *
     * @return the identity to which the permissions must be granted, or not
     */
    Identity getIdentity();

    /**
     * Returns all attributes within the current execution and runtime environment.
     *
     * @return the attributes within the current execution and runtime environment
     */
    Attributes getAttributes();
}

在这个接口中,策略可以获取:

  • 经过身份验证的 身份
  • 有关执行上下文和运行时环境的信息

身份 基于与授权请求一起发送的 OAuth2 访问令牌构建,此构造可以访问从原始令牌提取的所有声明。例如,如果您使用 协议映射程序 在 OAuth2 访问令牌中包含自定义声明,您也可以从策略访问此声明,并使用它来构建您的条件。

EvaluationContext 还允许您访问与执行和运行时环境相关的属性。目前,它们只是几个内置属性。

Expand
表 5.1. 执行和运行时属性
Name描述类型

kc.time.date_time

当前日期和时间

字符串.格式 MM/dd/yyyy hh:mm:s

kc.client.network.ip_address

客户端的 IPv4 地址

字符串

kc.client.network.host

客户端的主机名

字符串

kc.client.id

客户端 ID

字符串

kc.client.user_agent

'User-Agent' HTTP 标头的值

String[]

kc.realm.name

域的名称

字符串

Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。 了解我们当前的更新.

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

Theme

© 2026 Red Hat
返回顶部