Wildfly web.xml安全性约束使用ContainerRequestFilter阻止JAX-RS方法的基本auth头

Paw*_*dki 5 java web.xml servlets security-constraint wildfly

我正在开发的Web应用程序包含一些servlet以及JAX-RS Web服务.到目前为止,我使用ContainerRequestFilter来验证REST方法调用,但现在我还需要保护servlet,所以我决定使用web.xml来定义安全性约束.我的web.xml看起来像这样:

<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>rest</web-resource-name>
            <url-pattern>/rest/*</url-pattern>
        </web-resource-collection>
    </security-constraint>
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>protected</web-resource-name>
            <url-pattern>/protected/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <role-name>admin</role-name>
        </auth-constraint>
    </security-constraint>
    <security-role>
        <role-name>admin</role-name>
    </security-role>
    <security-role>
        <role-name>user</role-name>
    </security-role>
    <!-- Configure login to be HTTP Basic -->
    <login-config>
        <auth-method>BASIC</auth-method>
        <realm-name>Restricted Zone</realm-name>
    </login-config>
</web-app>
Run Code Online (Sandbox Code Playgroud)

如果我正确理解了web.xml的语法,我定义的意味着对于/ rest/*(我所有的JAX-RS方法都是)的访问权限就LoginModule而言是无限制的,并且对/ protected的访问权限都是/*path(我保留我的安全servlet)需要基本授权.

当我尝试打开其中一个安全servlet时,例如/ protected/test,我在浏览器中获得了基本的auth登录对话框,行为是正确的 - 如果我输入'admin'用户的凭据,我就可以访问.否则,我会收到"禁止"消息.

此外,当我尝试访问/ rest/path上的任何内容时,我没有得到任何基本的auth对话框,这就是我所期望的.但是,我在ContainerRequestFilter中获取的Authorization标头不是我在REST请求中发送的那个,而是我之前用于进入/ protected/servlet的那个.

以下是这个难题的其他部分:

standalone.xml(security-domains部分)

<security-domain name="PaloSecurityDomain" cache-type="default">
    <authentication>
        <login-module code="com.palo.security.PaloLoginModule" flag="required"/>
    </authentication>
</security-domain>
Run Code Online (Sandbox Code Playgroud)

的jboss-web.xml中

<?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
    <security-domain>PaloSecurityDomain</security-domain>
</jboss-web>
Run Code Online (Sandbox Code Playgroud)

PaloLoginModule.java

package com.palo.security;

import java.security.acl.Group;
import java.util.Set;

import javax.inject.Inject;
import javax.naming.NamingException;
import javax.security.auth.login.LoginException;

import org.apache.log4j.Logger;
import org.jboss.security.SimpleGroup;
import org.jboss.security.SimplePrincipal;
import org.jboss.security.auth.spi.UsernamePasswordLoginModule;

import com.palo.PaloRealmRole;
import com.palo.model.PaloRealmUser;
import com.palo.utils.CdiHelper;
import com.palo.utils.PasswordHandler;

public class PaloRealmLoginModule extends UsernamePasswordLoginModule {

  private static Logger logger = Logger
      .getLogger(PaloRealmLoginModule.class);

  @Inject
  private PaloRealmLogic realmLogic;

  @Override
  protected String getUsersPassword() throws LoginException {
    if (null == realmLogic) {
      try {
        CdiHelper.programmaticInjection(PaloRealmLoginModule.class,
            this);
      } catch (NamingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    logger.debug("Getting password for user " + super.getUsername());
    PaloRealmUser user = realmLogic.getUserByName(super.getUsername());
    if (null == user) {
      logger.error("User not found");
      throw new LoginException("User " + super.getUsername()
          + " not found");
    }
    logger.debug("Found " + user.getPassword());
    return user.getPassword();
  }

  @Override
  protected Group[] getRoleSets() throws LoginException {
    logger.debug("Getting roles for user " + super.getUsername());
    if (null == realmLogic) {
      try {
        CdiHelper.programmaticInjection(PaloRealmLoginModule.class,
            this);
      } catch (NamingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    PaloRealmUser user = realmLogic.getUserByName(super.getUsername());
    if (null == user) {
      throw new LoginException("User " + super.getUsername()
          + " not found");
    }
    Set<PaloRealmRole> roles = user.getRoles();
    Group[] groups = { new SimpleGroup("Roles") };
    for (PaloRealmRole role : roles) {
      logger.debug("Found role " + role.getRole());
      SimplePrincipal prole = new SimplePrincipal(role.getRole());
      groups[0].addMember(prole);
    }

    return groups;
  }

  @Override
  protected boolean validatePassword(String inputPassword,
      String expectedPassword) {
    logger.debug("Validating password " + inputPassword + "|"
        + expectedPassword);
    return PasswordHandler.getInstance().verifyPassword(inputPassword,
        expectedPassword);
  }

}
Run Code Online (Sandbox Code Playgroud)

SecurityInterceptor.java

package com.palo.web.rest;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.StringTokenizer;

import javax.annotation.security.DenyAll;
import javax.annotation.security.PermitAll;
import javax.inject.Inject;
import javax.json.JsonObjectBuilder;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;

import org.apache.log4j.Logger;
import org.jboss.resteasy.annotations.interception.ServerInterceptor;
import org.jboss.resteasy.core.Headers;
import org.jboss.resteasy.core.ResourceMethodInvoker;
import org.jboss.resteasy.core.ServerResponse;

import com.palo.analytics.GoogleAnalyticsEvent;
import com.palo.logic.UserLogic;
import com.palo.web.utils.HttpUtils;

@Provider
@ServerInterceptor
public class SecurityInterceptor implements ContainerRequestFilter {

  private static Logger logger = Logger.getLogger(SecurityInterceptor.class);

  private static final String AUTHORIZATION_PROPERTY = "Authorization";
  private static final ServerResponse ACCESS_DENIED = new ServerResponse(
      "Access denied for this resource", 401, new Headers<Object>());
  private static final ServerResponse ACCESS_DENIED_FOR_USER = new ServerResponse(
      "User not authorized", 401, new Headers<Object>());
  private static final ServerResponse ACCESS_FORBIDDEN = new ServerResponse(
      "Nobody can access this resource", 403, new Headers<Object>());

  @Inject
  private UserLogic ul;

  @Override
  /**
   * The request filter is called automatically called for each incoming request. It checks which method is being called by the client and, based on that method's annotations, restricts access, verifies the identity of the caller, checks the validity of the session token, etc.
   */
  public void filter(ContainerRequestContext requestContext)
      throws IOException {
    logger.debug("------------- request filter ------------");
    ResourceMethodInvoker methodInvoker = (ResourceMethodInvoker) requestContext
        .getProperty("org.jboss.resteasy.core.ResourceMethodInvoker");
    Method method = methodInvoker.getMethod();
    String methodName = method.getName();
    String uri = requestContext.getUriInfo().getPath();

    logger.debug("Accessing method " + methodName + " via URI " + uri);

    for (String str : requestContext.getPropertyNames()) {
      logger.debug(str);
    }

    // Get request headers
    final MultivaluedMap<String, String> headers = requestContext
        .getHeaders();
    for (String key : headers.keySet()) {
      for (String value : headers.get(key)) {
        logger.debug(key + " - " + value);
      }
    }

    // Access allowed for all
    if (method.isAnnotationPresent(PermitAll.class)) {
      return;
    }
    // Access denied for all
    if (method.isAnnotationPresent(DenyAll.class)) {
      requestContext.abortWith(ACCESS_FORBIDDEN);
      return;
    }

    // Fetch authorization header
    final List<String> authorization = headers.get(AUTHORIZATION_PROPERTY);

    // If no authorization information present; block access
    if (null == authorization || authorization.isEmpty()) {
      requestContext.abortWith(ACCESS_DENIED);
      return;
    }

    final String username = HttpUtils.getUsernameFromAuthorizationHeader(
        authorization, HttpUtils.AUTHENTICATION_SCHEME_BASIC);
    final String password = HttpUtils.getPasswordFromAuthenticationHeader(
        authorization, HttpUtils.AUTHENTICATION_SCHEME_BASIC);

    if (null == username || null == password || username.isEmpty()
        || password.isEmpty()) {
      requestContext.abortWith(ACCESS_DENIED_FOR_USER);
      return;
    }

    boolean authenticated = ul.authenticate(username, password);
    if (false == authenticated) {
      requestContext.abortWith(ACCESS_DENIED);
      return;
    } 
    return;
  }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用RESTClient for Firefox将REST请求发送到JAX-RS方法.由于我正在记录所有标题,我可以清楚地看到过滤器的内容,并且调用之间的值不会改变,即使我在RESTClient中更改它也是如此.更重要的是,即使我不在RESTClient中使用Authorization标头,该值仍然存在.

我的问题是为什么授权标题被阻止而且它没有被转发到我的过滤器?如果我删除web.xml文件,我会在ContainerRequestFilter中获得正确的Authorization标头.有没有办法将应用程序的/ rest部分移动到不受web.xml中login-config影响的区域?

任何帮助是极大的赞赏!

Zhe*_*nya 4

据我了解,如果您指定登录配置,它将用于 web-resource-collection 中指定的所有资源。在你的情况下, /rest/ 和 /protected/ 都是。

第一种方法 您可以做的一件事是修改您的登录模块,以便它将admin角色分配给那些提供了有效凭据的用户,并将anonymous角色分配给那些未提供有效凭据的用户。然后你可以像这样修改你的 web.xml

    <security-constraint>
        <web-resource-collection>
            <web-resource-name>rest</web-resource-name>
            <url-pattern>/rest/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <role-name>anonymous</role-name>
            <role-name>admin</role-name>
        </auth-constraint>
    </security-constraint>
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>protected</web-resource-name>
            <url-pattern>/protected/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <role-name>admin</role-name>
        </auth-constraint>
    </security-constraint>
Run Code Online (Sandbox Code Playgroud)


第二种方法 不是修改您的登录模块,而是向您的安全域添加一个登录模块,这将为anonymous每个人分配角色

第三种方法 使用自定义身份验证机制http://undertow.io/documentation/core/security.html BASIC身份验证机制期望用户以 Authorization: Basic: base64encodedCredentials 格式在 http 标头中发送凭据

使用自定义身份验证机制时,您可以访问请求路径,并且可以使自定义身份验证机制跳过对登录模块的调用,以防请求发送到您不希望受到保护的路径。但我认为这不是一个好方法,因为这些决定应该由登录模块+web.xml 做出。


第四种方法(不确定它是否有效,但希望它有效) 登录模块不会检查安全约束中未指定的资源。因此,要使 /rest/ 资源不受保护,请从 web.xml 中删除这些行:

<security-constraint>
        <web-resource-collection>
            <web-resource-name>rest</web-resource-name>
            <url-pattern>/rest/*</url-pattern>
        </web-resource-collection>
    </security-constraint>
Run Code Online (Sandbox Code Playgroud)