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();
}
Copy to Clipboard Toggle word wrap

在处理授权请求时,红帽构建的 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();
}
Copy to Clipboard Toggle word wrap

在这个界面中,策略可以获取:

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

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

EvaluationContext 还可让您访问与执行和运行时环境相关的属性。现在,只有几个内置属性。

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

kc.time.date_time

当前日期和时间

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

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

© 2025 Red Hat