2.2. 使用安全域对应用程序用户进行身份验证和授权


使用引用安全域的安全域来验证和授权应用用户。开发应用程序的流程仅作为示例提供。

您可以创建一个简单的 Web 应用来遵循配置安全域示例。

注意

以下流程仅作为示例提供。如果您已有要保护的应用程序,则可以跳过这些步骤,直接来到 向应用程序添加身份验证和授权

要创建一个 web 应用,请创建一个具有所需依赖项和目录结构的 Maven 项目。

先决条件

流程

  1. 使用 mvn 命令建立一个 Maven 项目。该命令创建项目的目录结构以及 pom.xml 配置文件。

    语法

    $ mvn archetype:generate \
    -DgroupId=${group-to-which-your-application-belongs} \
    -DartifactId=${name-of-your-application} \
    -DarchetypeGroupId=org.apache.maven.archetypes \
    -DarchetypeArtifactId=maven-archetype-webapp \
    -DinteractiveMode=false
    Copy to Clipboard Toggle word wrap

    Example

    $ mvn archetype:generate \
    -DgroupId=com.example.app \
    -DartifactId=simple-webapp-example \
    -DarchetypeGroupId=org.apache.maven.archetypes \
    -DarchetypeArtifactId=maven-archetype-webapp \
    -DinteractiveMode=false
    Copy to Clipboard Toggle word wrap

  2. 进入到应用程序根目录:

    语法

    $ cd <name-of-your-application>
    Copy to Clipboard Toggle word wrap

    Example

    $ cd simple-webapp-example
    Copy to Clipboard Toggle word wrap

  3. 将生成的 pom.xml 文件的内容替换为以下文本:

    <?xml version="1.0" encoding="UTF-8"?>
    
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>com.example.app</groupId>
      <artifactId>simple-webapp-example</artifactId>
      <version>1.0-SNAPSHOT</version>
      <packaging>war</packaging>
    
      <name>simple-webapp-example Maven Webapp</name>
      <!-- FIXME change it to the project's website -->
      <url>http://www.example.com</url>
    
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
      </properties>
    
      <dependencies>
        <dependency>
          <groupId>jakarta.servlet</groupId>
          <artifactId>jakarta.servlet-api</artifactId>
          <version>6.0.0</version>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>org.wildfly.security</groupId>
          <artifactId>wildfly-elytron-auth-server</artifactId>
          <version>1.19.0.Final</version>
        </dependency>
      </dependencies>
    
      <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
          <plugin>
            <groupId>org.wildfly.plugins</groupId>
            <artifactId>wildfly-maven-plugin</artifactId>
            <version>2.1.0.Final</version>
          </plugin>
        </plugins>
      </build>
    
    </project>
    Copy to Clipboard Toggle word wrap

验证

  • 在应用程序根目录中,输入以下命令:

    $ mvn install
    Copy to Clipboard Toggle word wrap

    您会看到类似如下的输出:

    ...
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 0.795 s
    [INFO] Finished at: 2022-04-28T17:39:48+05:30
    [INFO] ------------------------------------------------------------------------
    Copy to Clipboard Toggle word wrap

现在,您可以创建一个 web 应用程序。

2.2.1.2. 创建一个 Web 应用程序

创建一个 Web 应用程序,其中包含一个 servlet,它将返回从登录的用户主体和属性中获取的用户名。如果没有登录的用户,servlet 将返回文本"NO AUTHENTICATED USER"。

先决条件

  • 您已创建了一个 Maven 项目。
  • JBoss EAP 正在运行。

流程

  1. 创建一个用于存储 Java 文件的目录。

    语法

    $ mkdir -p src/main/java/<path_based_on_artifactID>
    Copy to Clipboard Toggle word wrap

    Example

    $ mkdir -p src/main/java/com/example/app
    Copy to Clipboard Toggle word wrap

  2. 前往新目录。

    语法

    $ cd src/main/java/<path_based_on_artifactID>
    Copy to Clipboard Toggle word wrap

    Example

    $ cd src/main/java/com/example/app
    Copy to Clipboard Toggle word wrap

  3. 使用以下内容创建一个 securedServlet.java 文件:

    package com.example.app;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.security.Principal;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Set;
    
    import jakarta.servlet.ServletException;
    import jakarta.servlet.annotation.WebServlet;
    import jakarta.servlet.http.HttpServlet;
    import jakarta.servlet.http.HttpServletRequest;
    import jakarta.servlet.http.HttpServletResponse;
    import org.wildfly.security.auth.server.SecurityDomain;
    import org.wildfly.security.auth.server.SecurityIdentity;
    import org.wildfly.security.authz.Attributes;
    import org.wildfly.security.authz.Attributes.Entry;
    /**
     * A simple secured HTTP servlet. It returns the user name and
     * attributes obtained from the logged-in user's Principal. If
     * there is no logged-in user, it returns the text
     * "NO AUTHENTICATED USER".
     */
    
    @WebServlet("/secured")
    public class SecuredServlet extends HttpServlet {
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            try (PrintWriter writer = resp.getWriter()) {
    
            	Principal user = req.getUserPrincipal();
            	SecurityIdentity identity = SecurityDomain.getCurrent().getCurrentSecurityIdentity();
            	Attributes identityAttributes = identity.getAttributes();
            	Set <String> keys = identityAttributes.keySet();
            	String attributes = "<ul>";
    
            	for (String attr : keys) {
            		attributes += "<li> " +  attr + " : " + identityAttributes.get(attr).toString() + "</li>";
            	}
    
            	attributes+="</ul>";
            	writer.println("<html>");
            	writer.println("  <head><title>Secured Servlet</title></head>");
            	writer.println("  <body>");
            	writer.println("    <h1>Secured Servlet</h1>");
            	writer.println("    <p>");
            	writer.print(" Current Principal '");
            	writer.print(user != null ? user.getName() : "NO AUTHENTICATED USER");
            	writer.print("'");
            	writer.print(user != null ? "\n" + attributes : "");
            	writer.println("    </p>");
            	writer.println("  </body>");
            	writer.println("</html>");
            }
        }
    
    }
    Copy to Clipboard Toggle word wrap
  4. 在应用程序根目录中,使用以下命令编译应用程序:

    $ mvn package
    ...
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 1.015 s
    [INFO] Finished at: 2022-04-28T17:48:53+05:30
    [INFO] ------------------------------------------------------------------------
    Copy to Clipboard Toggle word wrap
  5. 部署应用。

    $ mvn wildfly:deploy
    Copy to Clipboard Toggle word wrap

验证

  • 在浏览器中,导航到 http://localhost:8080/simple-webapp-example/secured

    您会收到以下信息:

    Secured Servlet
    Current Principal 'NO AUTHENTICATED USER'
    Copy to Clipboard Toggle word wrap

    因为没有添加验证机制,所以您可以访问应用程序。

现在,您可以使用安全域来保护这个应用程序,这样只有经过身份验证的用户才可以访问它。

2.2.2. 向应用程序添加身份验证和授权

您可以使用安全域向 Web 应用程序添加身份验证和授权,以对其进行保护。要在添加身份验证和授权后访问 web 应用程序,用户必须输入登录凭证。

先决条件

  • 您已创建了一个引用安全域的安全域。
  • 您已在 JBoss EAP 上部署了应用程序。
  • JBoss EAP 正在运行。

流程

  1. undertow 子系统 中配置一个application-security-domain

    语法

    /subsystem=undertow/application-security-domain=<application_security_domain_name>:add(security-domain=<security_domain_name>)
    Copy to Clipboard Toggle word wrap

    Example

    /subsystem=undertow/application-security-domain=exampleApplicationSecurityDomain:add(security-domain=exampleSecurityDomain)
    {"outcome" => "success"}
    Copy to Clipboard Toggle word wrap

  2. 配置应用程序的 web.xml 以保护应用程序资源。

    语法

    <!DOCTYPE web-app PUBLIC
     "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
     "http://java.sun.com/dtd/web-app_2_3.dtd" >
    
    <web-app>
    
     <!-- Define the security constraints for the application resources.
          Specify the URL pattern for which a challenge is -->
    
     <security-constraint>
            <web-resource-collection>
                <web-resource-name><!-- Name of the resources to protect --></web-resource-name>
                <url-pattern> <!-- The URL to protect  --></url-pattern>
            </web-resource-collection>
    
            <!-- Define the role that can access the protected resource -->
            <auth-constraint>
                <role-name> <!-- Role name as defined in the security domain --></role-name>
                <!-- To disable authentication you can use the wildcard *
                	 To authenticate but allow any role, use the wildcard **. -->
            </auth-constraint>
        </security-constraint>
    
        <login-config>
            <auth-method>
            	<!-- The authentication method to use. Can be:
            		BASIC
            		CLIENT-CERT
            		DIGEST
            		FORM
            		SPNEGO
            	 -->
            </auth-method>
    
            <realm-name><!-- The name of realm to send in the challenge  --></realm-name>
        </login-config>
     </web-app>
    Copy to Clipboard Toggle word wrap

    Example

    <!DOCTYPE web-app PUBLIC
     "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
     "http://java.sun.com/dtd/web-app_2_3.dtd" >
    
    <web-app>
    
     <!-- Define the security constraints for the application resources.
          Specify the URL pattern for which a challenge is -->
    
     <security-constraint>
            <web-resource-collection>
                <web-resource-name>all</web-resource-name>
                <url-pattern>/*</url-pattern>
            </web-resource-collection>
    
            <!-- Define the role that can access the protected resource -->
            <auth-constraint>
                <role-name>Admin</role-name>
                <!-- To disable authentication you can use the wildcard *
                	 To authenticate but allow any role, use the wildcard **. -->
            </auth-constraint>
        </security-constraint>
    
        <login-config>
            <auth-method>BASIC</auth-method>
            <realm-name>exampleSecurityRealm</realm-name>
        </login-config>
     </web-app>
    Copy to Clipboard Toggle word wrap

    注意

    您可以使用不同的 auth-method

  3. 通过在应用程序中创建一个 jboss-web.xml 文件,或者在 undertow 子系统中设置默认安全域,将应用程序配置为使用安全域。

    • 在应用程序的 WEB-INF 目录中创建引用 application-security-domainjboss-web.xml 文件。

      语法

      <jboss-web>
        <security-domain> <!-- The security domain to associate with the application --></security-domain>
      </jboss-web>
      Copy to Clipboard Toggle word wrap

      Example

      <jboss-web>
        <security-domain>exampleApplicationSecurityDomain</security-domain>
      </jboss-web>
      Copy to Clipboard Toggle word wrap

    • undertow 子系统中,为应用程序设置默认安全域。

      语法

      /subsystem=undertow:write-attribute(name=default-security-domain,value=<application_security_domain_to_use>)
      Copy to Clipboard Toggle word wrap

      Example

      /subsystem=undertow:write-attribute(name=default-security-domain,value=exampleApplicationSecurityDomain)
      {
          "outcome" => "success",
          "response-headers" => {
              "operation-requires-reload" => true,
              "process-state" => "reload-required"
          }
      }
      Copy to Clipboard Toggle word wrap

  4. 重新加载服务器。

    reload
    Copy to Clipboard Toggle word wrap

验证

  1. 在应用程序根目录中,使用以下命令编译应用程序:

    $ mvn package
    ...
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 1.015 s
    [INFO] Finished at: 2022-04-28T17:48:53+05:30
    [INFO] ------------------------------------------------------------------------
    Copy to Clipboard Toggle word wrap
  2. 部署应用。

    $ mvn wildfly:deploy
    Copy to Clipboard Toggle word wrap
  3. 在浏览器中,导航到 http://localhost:8080/simple-webapp-example/secured。您会收到一个登录提示,确认现在需要身份验证才能访问应用程序。

现在,您的应用程序已使用安全域进行了保护,用户可以在身份验证后登录。另外,只有具有指定角色的用户才可以访问应用程序。

返回顶部
Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

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

让开源更具包容性

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

關於紅帽

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

Theme

© 2025 Red Hat