5.11. 策略评估 API


使用 JavaScript 编写基于规则的策略时,红帽单点登录提供了评估 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

在处理授权请求时,Red Hat Single Sign-On 会创建 评估 实例,然后再评估任何策略。然后,此实例将传递到每个策略,以确定访问权限是否为 GRANT 还是 DENY

通过调用 Evaluation 实例上的 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/yyy 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