2.2. 보안 도메인을 사용하여 애플리케이션 사용자를 인증 및 권한 부여
보안 영역을 참조하는 보안 도메인을 사용하여 애플리케이션 사용자를 인증하고 권한을 부여합니다. 애플리케이션 개발 절차는 예제로만 제공됩니다.
2.2.1. 집계-realm을 위한 간단한 웹 애플리케이션 개발 링크 복사링크가 클립보드에 복사되었습니다!
보안 영역 구성 예제와 함께 간단한 웹 애플리케이션을 생성할 수 있습니다.
다음 절차는 예제로만 제공됩니다. 보안하려는 애플리케이션이 이미 있는 경우 이를 건너뛰고 애플리케이션에 인증 및 권한 부여 추가로 직접 이동할 수 있습니다.
2.2.1.1. 웹 애플리케이션 개발을 위한 maven 프로젝트 생성 링크 복사링크가 클립보드에 복사되었습니다!
웹 애플리케이션을 생성하려면 필수 종속성 및 디렉터리 구조가 포함된 Maven 프로젝트를 생성합니다.
사전 요구 사항
- Maven이 설치되어 있어야 합니다. 자세한 내용은 Apache Maven 다운로드를 참조하십시오.
프로세스
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예제
$ mvn archetype:generate \ -DgroupId=com.example.app \ -DartifactId=simple-webapp-example \ -DarchetypeGroupId=org.apache.maven.archetypes \ -DarchetypeArtifactId=maven-archetype-webapp \ -DinteractiveMode=false애플리케이션 루트 디렉터리로 이동합니다.
구문
$ cd <name-of-your-application>예제
$ cd simple-webapp-example생성된
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>
검증
애플리케이션 루트 디렉터리에 다음 명령을 입력합니다.
$ mvn install다음과 유사한 출력이 표시됩니다.
... [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 0.795 s [INFO] Finished at: 2022-04-28T17:39:48+05:30 [INFO] ------------------------------------------------------------------------
이제 웹 애플리케이션을 생성할 수 있습니다.
2.2.1.2. 웹 애플리케이션 생성 링크 복사링크가 클립보드에 복사되었습니다!
로그인한 사용자의 주체 및 특성에서 얻은 사용자 이름을 반환하는 서블릿이 포함된 웹 애플리케이션을 생성합니다. 로그인한 사용자가 없는 경우 서블릿은 "NO AUTHENTICATED USER" 텍스트를 반환합니다.
사전 요구 사항
- Maven 프로젝트를 생성했습니다.
- JBoss EAP가 실행 중입니다.
프로세스
Java 파일을 저장할 디렉터리를 만듭니다.
구문
$ mkdir -p src/main/java/<path_based_on_artifactID>예제
$ mkdir -p src/main/java/com/example/app새 디렉터리로 이동합니다.
구문
$ cd src/main/java/<path_based_on_artifactID>예제
$ cd src/main/java/com/example/app다음 콘텐츠를 사용하여
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>"); } } }애플리케이션 루트 디렉터리에서 다음 명령을 사용하여 애플리케이션을 컴파일합니다.
$ mvn package ... [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 1.015 s [INFO] Finished at: 2022-04-28T17:48:53+05:30 [INFO] ------------------------------------------------------------------------애플리케이션을 배포합니다.
$ mvn wildfly:deploy
검증
브라우저에서
http://localhost:8080/simple-webapp-example/secured로 이동합니다.다음 메시지가 표시됩니다.
Secured Servlet Current Principal 'NO AUTHENTICATED USER'인증 메커니즘이 추가되지 않으므로 애플리케이션에 액세스할 수 있습니다.
이제 인증된 사용자만 액세스할 수 있도록 보안 도메인을 사용하여 이 애플리케이션을 보호할 수 있습니다.
2.2.2. 애플리케이션에 인증 및 권한 부여 추가 링크 복사링크가 클립보드에 복사되었습니다!
보안 도메인을 사용하여 웹 애플리케이션에 인증 및 권한 부여를 추가하여 보호할 수 있습니다. 인증 및 권한 부여를 추가한 후 웹 애플리케이션에 액세스하려면 사용자가 로그인 자격 증명을 입력해야 합니다.
사전 요구 사항
- 보안 영역을 참조하는 보안 도메인을 생성했습니다.
- JBoss EAP에 애플리케이션을 배포했습니다.
- JBoss EAP가 실행 중입니다.
프로세스
undertow 하위 시스템에서application-security-domain을 구성합니다.구문
/subsystem=undertow/application-security-domain=<application_security_domain_name>:add(security-domain=<security_domain_name>)예제
/subsystem=undertow/application-security-domain=exampleApplicationSecurityDomain:add(security-domain=exampleSecurityDomain) {"outcome" => "success"}애플리케이션 리소스를 보호하도록 애플리케이션의
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>예제
<!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>참고다른
auth-method를 사용할 수 있습니다.애플리케이션에
jboss-web.xml파일을 생성하거나undertow하위 시스템에서 기본 보안 도메인을 설정하여 애플리케이션을 구성하십시오.애플리케이션의 article-
INF 디렉터리에을 참조하는application-security-domainjboss-web.xml파일을 만듭니다.구문
<jboss-web> <security-domain> <!-- The security domain to associate with the application --></security-domain> </jboss-web>예제
<jboss-web> <security-domain>exampleApplicationSecurityDomain</security-domain> </jboss-web>애플리케이션의
undertow하위 시스템에서 기본 보안 도메인을 설정합니다.구문
/subsystem=undertow:write-attribute(name=default-security-domain,value=<application_security_domain_to_use>)예제
/subsystem=undertow:write-attribute(name=default-security-domain,value=exampleApplicationSecurityDomain) { "outcome" => "success", "response-headers" => { "operation-requires-reload" => true, "process-state" => "reload-required" } }
서버를 다시 로드합니다.
reload
검증
애플리케이션 루트 디렉터리에서 다음 명령을 사용하여 애플리케이션을 컴파일합니다.
$ mvn package ... [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 1.015 s [INFO] Finished at: 2022-04-28T17:48:53+05:30 [INFO] ------------------------------------------------------------------------애플리케이션을 배포합니다.
$ mvn wildfly:deploy-
브라우저에서
http://localhost:8080/simple-webapp-example/secured로 이동합니다. 이제 애플리케이션에 액세스하려면 인증이 필요함을 확인하는 로그인 프롬프트가 표시됩니다.
이제 보안 도메인을 사용하여 애플리케이션이 보호되며 사용자는 인증 후만 로그인할 수 있습니다. 또한 지정된 역할이 있는 사용자만 애플리케이션에 액세스할 수 있습니다.