10.4. 开发自定义 HTTP 机制


当 Elytron 用于保护 Web 应用时,可以实施可以使用 elytron 子系统注册的自定义 HTTP 身份验证机制。然后,也可以覆盖部署中的配置,以利用这种机制,而无需修改部署。

重要

所有自定义 HTTP 机制都需要实施 HttpServerAuthenticationMechanism 接口。

通常,对于 HTTP 机制,会调用 evaluation Request 方法来处理在 HTTPServerRequest 对象中传递的请求。机制处理请求并使用请求中的以下回调方法之一来指示结果:

  • authenticationComplete - 机制成功验证请求。
  • Authentication Failed - 身份验证尝试失败,但失败。
  • Authentication InProgress - 开始身份验证,但还需要额外往返。
  • badRequest - 此机制的身份验证失败验证请求。
  • noAuthenticationInProgress - 机制没有尝试任何身份验证阶段。

在创建了实施 HttpServerAuthenticationMechanism 接口的自定义 HTTP 机制后,下一步是创建一个工厂来返回此机制的实例。工厂必须实施 HttpAuthenticationFactory 接口。实施工厂中最重要的步骤是重复检查请求的机制的名称。如果工厂无法创建所需的机制,则工厂返回 null 非常重要。机制工厂也可以考虑传输的映射中的属性,以确定它是否能创建请求的机制。

有两种不同的方法可用来公告可供使用的机制工厂。

  • 第一种方法是实施 java.security.Provider,其支持的每种机制都注册为一次 HttpAuthenticationFactory
  • 第二种方法是使用 java.util.ServiceLoader 来发现工厂。要做到这一点,META-INF/services 下应当添加一个名为 org.wildfly.security.http.HttpServerAuthenticationMechanismFactory 的文件。此文件中唯一需要的内容是工厂实施的完全限定类名称。

然后,这个机制可以作为可被使用的模块安装到应用程序服务器中:

module add --name=org.wildfly.security.examples.custom-http --resources=/path/to/custom-http-mechanism.jar --dependencies=org.wildfly.security.elytron,javax.api
Copy to Clipboard Toggle word wrap

使用自定义 HTTP 机制

  1. 添加自定义模块。

    /subsystem=elytron/service-loader-http-server-mechanism-factory=custom-factory:add(module=org.wildfly.security.examples.custom-http)
    Copy to Clipboard Toggle word wrap
  2. 添加 http-authentication-factory,将机制工厂绑定到将用于身份验证 的安全域

    /subsystem=elytron/http-authentication-factory=custom-mechanism:add(http-server-mechanism-factory=custom-factory,security-domain=ApplicationDomain,mechanism-configurations=[{mechanism-name=custom-mechanism}])
    Copy to Clipboard Toggle word wrap
  3. 更新 application-security-domain 资源,以使用新的 http-authentication-factory

    注意

    部署应用时,它默认使用 other 安全域。因此,您需要向应用添加映射,以将其映射到 Elytron HTTP 身份验证工厂。

    /subsystem=undertow/application-security-domain=other:add(http-authentication-factory=application-http-authentication)
    Copy to Clipboard Toggle word wrap

    现在,可以更新 application-security-domain 资源以使用新的 http-authentication-factory

    /subsystem=undertow/application-security-domain=other:write-attribute(name=http-authentication-factory,value=custom-mechanism)
    
    /subsystem=undertow/application-security-domain=other:write-attribute(name=override-deployment-config,value=true)
    Copy to Clipboard Toggle word wrap

    请注意,上述命令将覆盖部署配置。这意味着,即使部署已配置为使用不同的机制,也会使用 http-authentication-factory 中的机制。因此,可以在不需要修改部署本身的情况下覆盖部署中的配置,从而利用自定义机制。

  4. 重新加载服务器

    reload
    Copy to Clipboard Toggle word wrap
返回顶部
Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

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

让开源更具包容性

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

關於紅帽

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

Theme

© 2025 Red Hat