1

我创建了一个自定义 LoginModule 来验证 mongoDB 集合中存在的用户。在我的情况下,我需要每页一个角色...我已经使用 JSF 的 JAAS 身份验证,但在这种情况下,它没有按预期工作...它总是返回 403 错误(禁止)。URL 的映射显然是可以的。

这是我的页面层次结构:

  • 应用程序 <-root
    • 页面
      • 我的受保护页面(每页一个角色)
    • 登录.html
    • login_error.html
    • 索引.html

按照我的配置:

jboss-web.xml

<jboss-web>
    <security-domain>nfceSecurityDomain</security-domain>
    <disable-audit>true</disable-audit>
</jboss-web>

web.xml

<session-config>
  <session-timeout>30</session-timeout>
</session-config>

<login-config>
     <auth-method>FORM</auth-method>
     <form-login-config>
          <form-login-page>/app/login.html</form-login-page>
          <form-error-page>/app/login_error.html</form-error-page>
     </form-login-config>
</login-config>

<security-role>
   <role-name>VISUALIZAR_NOTAS</role-name>
</security-role>
<security-role>
   <role-name>GESTAO_CERTIFICADO</role-name>
</security-role>
<security-role>
   <role-name>GESTAO_EMPRESA</role-name>
</security-role>
<security-role>
   <role-name>DOWNLOAD_XML</role-name>
</security-role>
<security-role>
   <role-name>INUTILIZACAO</role-name>
</security-role>

<security-constraint>
    <web-resource-collection>
         <web-resource-name>index</web-resource-name>
         <url-pattern>/app/index.html</url-pattern>
         <http-method>POST</http-method>
         <http-method>GET</http-method>
         <http-method>PUT</http-method>
         <http-method>DELETE</http-method>
    </web-resource-collection>
    <auth-constraint>
            <role-name>VISUALIZAR_NOTAS</role-name>
    </auth-constraint>
</security-constraint>
<security-constraint>
    <web-resource-collection>
         <web-resource-name>orderList</web-resource-name>
         <url-pattern>/app/pages/orderlist.html</url-pattern>
         <http-method>POST</http-method>
         <http-method>GET</http-method>
         <http-method>PUT</http-method>
         <http-method>DELETE</http-method>
    </web-resource-collection>
    <auth-constraint>
         <role-name>VISUALIZAR_NOTAS</role-name>
    </auth-constraint>
</security-constraint>
<security-constraint>
   <web-resource-collection>
       <web-resource-name>certificateConfigurations</web-resource-name>
       <url-pattern>/app/pages/certifiedlist.html</url-pattern>
        <http-method>POST</http-method>
        <http-method>GET</http-method>
        <http-method>PUT</http-method>
        <http-method>DELETE</http-method>
   </web-resource-collection>
   <auth-constraint>
       <role-name>GESTAO_CERTIFICADO</role-name>
   </auth-constraint>
</security-constraint>
<security-constraint>
   <web-resource-collection>
       <web-resource-name>enterpriseConfigurations</web-resource-name>
       <url-pattern>/app/pages/enterpriselist.html</url-pattern>
        <http-method>POST</http-method>
        <http-method>GET</http-method>
        <http-method>PUT</http-method>
        <http-method>DELETE</http-method>
   </web-resource-collection>
   <auth-constraint>
       <role-name>GESTAO_EMPRESA</role-name>
   </auth-constraint>
</security-constraint>
<security-constraint>
   <web-resource-collection>
       <web-resource-name>xmlDownload</web-resource-name>
       <url-pattern>/app/pages/orderdownload.html</url-pattern>
        <http-method>POST</http-method>
        <http-method>GET</http-method>
        <http-method>PUT</http-method>
        <http-method>DELETE</http-method>
   </web-resource-collection>
   <auth-constraint>
       <role-name>DOWNLOAD_XML</role-name>
   </auth-constraint>
</security-constraint>
<security-constraint>
   <web-resource-collection>
       <web-resource-name>invalidate</web-resource-name>
       <url-pattern>/app/pages/orderInvalidate.html</url-pattern>
        <http-method>POST</http-method>
        <http-method>GET</http-method>
        <http-method>PUT</http-method>
        <http-method>DELETE</http-method>
   </web-resource-collection>
   <auth-constraint>
       <role-name>INUTILIZACAO</role-name>
   </auth-constraint>
</security-constraint>

独立的.xml

<subsystem xmlns="urn:jboss:domain:security:1.2">
            <security-domains>
                <security-domain name="nfceSecurityDomain" cache-type="default">
                    <authentication>
                        <login-module code="br.com.ciss.nfce.security.JAASLoginModule" flag="required"/>
                    </authentication>
                </security-domain>
            </security-domains>
        </subsystem>

这是我的 LoginModule 实现,用于从 MongoDB 获取用户和角色:

public class JAASLoginModule implements LoginModule {

    private static final Logger LOG = Logger.getLogger(JAASLoginModule.class);

    private Subject subject;
    private CallbackHandler callbackHandler;
    private Map sharedState;
    private Map options;

    private boolean succeeded = false;
    private boolean commitSucceeded = false;

    private String username = null;
    private String _idUser = "";
    private char[] password = null;

    private Principal userPrincipal = null;
    private Principal passwordPrincipal = null;

    private ConnectionMongoUtil connectionMongoUtil;

    public JAASLoginModule() {
        super();
    }

    @Override
    public void initialize(Subject subject, CallbackHandler callbackHandler,
            Map<String, ?> sharedState, Map<String, ?> options) {
        this.subject = subject;
        this.callbackHandler = callbackHandler;
        this.sharedState = sharedState;
        this.options = options;
    }

    @Override
    public boolean login() throws LoginException {

        if (callbackHandler == null) {
            throw new LoginException("Error: no CallbackHandler available "
                    + "to garner authentication information from the user");
        }
        Callback[] callbacks = new Callback[2];
        callbacks[0] = new NameCallback("username");
        callbacks[1] = new PasswordCallback("password: ", false);

        try {
            callbackHandler.handle(callbacks);
            username = ((NameCallback) callbacks[0]).getName();
            password = ((PasswordCallback) callbacks[1]).getPassword();

            if (username == null || password == null) {
                LOG.error("Callback handler does not return login data properly");
                throw new LoginException(
                        "Callback handler does not return login data properly");
            }

            if (isValidUser()) { // validate user.
                succeeded = true;
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (UnsupportedCallbackException e) {
            e.printStackTrace();
        }

        return false;
    }

    @Override
    public boolean commit() throws LoginException {
        if (succeeded == false) {
            return false;
        } else {
            userPrincipal = new JAASUserPrincipal(username);
            if (!subject.getPrincipals().contains(userPrincipal)) {
                subject.getPrincipals().add(userPrincipal);
                LOG.debug("User principal added:" + userPrincipal);
            }
            passwordPrincipal = new JAASPasswordPrincipal(new String(password));
            if (!subject.getPrincipals().contains(passwordPrincipal)) {
                subject.getPrincipals().add(passwordPrincipal);
                LOG.debug("Password principal added: " + passwordPrincipal);
            }

            List<String> roles = getRoles();
            for (String role : roles) {
                Principal rolePrincipal = new JAASRolePrincipal(role);
                if (!subject.getPrincipals().contains(rolePrincipal)) {
                    subject.getPrincipals().add(rolePrincipal);
                    LOG.debug("Role principal added: " + rolePrincipal);
                }
            }

            commitSucceeded = true;
            LOG.info("Login subject were successfully populated with principals and roles");
            return true;
        }
    }

    @Override
    public boolean abort() throws LoginException {
        if (succeeded == false) {
            return false;
        } else if (succeeded == true && commitSucceeded == false) {
            succeeded = false;
            username = null;
            if (password != null) {
                password = null;
            }
            userPrincipal = null;
        } else {
            logout();
        }
        return true;
    }

    @Override
    public boolean logout() throws LoginException {
        subject.getPrincipals().remove(userPrincipal);
        succeeded = false;
        succeeded = commitSucceeded;
        username = null;
        if (password != null) {
            for (int i = 0; i < password.length; i++) {
                password[i] = ' ';
                password = null;
            }
        }
        userPrincipal = null;
        return true;
    }

    private boolean isValidUser() throws LoginException {

        try {
            BasicDBObject search = new BasicDBObject();
            search.put("email", username);
            connectionMongoUtil = new ConnectionMongoUtil();
            DBObject user = connectionMongoUtil.getCollection("User").findOne(search);

            if (user == null){
                LOG.debug("USUÁRIO NÃO LOCALIZADO!");
                return false;
            }else{
                if ( new String(password).equals(user.get("password"))){
                    _idUser = user.get("_id").toString();
                    return true;
                }else{
                    LOG.debug("SENHA INVÁLIDA PARA O USUÁRIO " + username);
                }
            }

            return false;
        } catch (Exception e) {
            LOG.error("Error when loading user " + username + " from the database \n", e);
        }

        return false;
    }

    /**
     * Returns list of roles assigned to authenticated user.
     * 
     * @return
     */
    private List<String> getRoles() {
        BasicDBObject search = new BasicDBObject();
        search.put("_idUser", _idUser);
        DBObject userModules = connectionMongoUtil.getCollection("UserModules").findOne(search);
        String jsonArrayModules = userModules.get("_idModules").toString();

        String[] modules = null;
        try {
            modules = new ObjectMapper().readValue(jsonArrayModules, String[].class);
        } catch (IOException e) {
            e.printStackTrace();
        }

        List<String> modulesList = new ArrayList<String>();
        for (String _idModule : modules) {
            DBObject module = connectionMongoUtil.getCollection("Module").findOne(new BasicDBObject("_id", new ObjectId(_idModule)));
            if (module != null){
                modulesList.add(module.get("name").toString());
            }
        }

        return modulesList;
    }
}

我在standalone.xml中添加了以下属性,以查看JAAS生成的日志,并且没有任何错误日志...

<logger category="org.jboss.security">
    <level name="ALL"/>
</logger>

在我的 MongoDB 集合中,我已将所有角色添加到我的用户,当我尝试登录时,我可以登录,但是所有页面都被锁定,返回 403 错误。

任何人都可以帮助我吗?也许这只是导致403错误的一个小细节......

感谢您的关注!

4

3 回答 3

0

解决这种情况的唯一方法是通过 Spring Security 更改 JAAS :)

于 2014-08-01T16:44:33.567 回答
0

你有没有试过在wildfly部署你的模块 http://www.mastertheboss.com/jboss-server/jboss-security/configuring-a-mongodb-login-module

于 2015-08-18T17:29:49.353 回答
0

我知道这是一个旧线程,但仍然没有一个好的解决方案。

我有同样的问题......

一些上下文:我有一个使用 JAAS(直接实现 javax.security.auth.spi.LoginModule)在 Tomcat7 上顺利运行的“健康”Java Web 应用程序。然后出现了一个客户要求:“它必须在 JBoss 7.1.1 上运行”WTF?甚至是次要版本和补丁!?!

动手:所以我做了所有的配置,Java 8 代码和 JAX-RS 有一些缺点,但这是另一个故事,最终我的应用程序在 JBoss 7.1.1 中成功部署。

问题:我可以在控制台中看到登录成功,但所有请求都返回 HTTP 403。

在调试所有主体(CallerPrincipal 和 UserRoles)时都可以。

另外,我有一个用于编排的抽象 BaseServlet,所有请求都应该遍历它,但是在到达它之前发生了 HTTP 403...

解决方案:所以我注意到所有关于 JAAS 的 JBoss 文档都建议开发人员扩展他们定制的 LoginModules,所以我开始挖掘。

org.jboss.security.auth.spi.AbstractServerLoginModule 使用他们所谓的“存储身份和角色的 JBossSX 标准主题使用模式”。

我没有深入解释这种模式,但我已经意识到在容器端包装身份验证过程的“JBossWebRealm”需要一个名为“Roles”的 java.security.acl.Group 实现,其中包含所有委托人(CallerPrincipal和 UserRoles)作为成员(The Membership Of The JAASRealm)。

该对象用于安全检查。

故事结束,我已将此方法添加到我的 LoginModule 实现中:

public boolean commit() throws LoginException {

    // some validation code here

    Set<Principal> principals = subject.getPrincipals();

    // ensure principals contains (CallerPrincipal and UserRoles)

    createRolesGroup(principals);

    return true;
}

private void createRolesGroup(Set<Principal> principals) {

    // Thee java.security.acl.Group implementation
    SecurityGroup rolesGroup = new SecurityGroup("Roles");

    Iterator<Principal> iter = principals.iterator();

    while(iter.hasNext()) {
        Object principal = iter.next();
        if(!(principal instanceof Group)){
        rolesGroup.addMember((Principal)principal);
    }

    principals.add(rolesGroup);
}

并且像魅力一样工作。

希望能帮助到你。

于 2016-07-15T15:23:33.210 回答