isUserInRole有时会返回false

时间:2013-02-16 16:48:57

标签: java jaas

我正在开发我的第一个Jsf,Jaas,JPA,JBoss应用程序,现在我遇到了这个麻烦。我在JBoss中创建了两个安全域:

<security-domain name="Database" cache-type="default">
<authentication>
    <login-module code="org.jboss.security.auth.spi.DatabaseServerLoginModule" flag="required">
        <module-option name="dsJndiName" value="java:jboss/JaasDS"/>
        <module-option name="principalsQuery" value="select password from user where mail=?"/>
        <module-option name="rolesQuery" value="select role, 'Roles'   from user u where u.mail=?"/>
    </login-module>
</authentication>
</security-domain>
<security-domain name="Custom" cache-type="default">
  <authentication>
    <login-module code="demo.SampleLoginModule" flag="required"/>
  </authentication>
</security-domain>

如果我使用“数据库”域,一切正常,而如果我使用“自定义”域,则无法将该角色设置为主体。

我的SampleLoginModule

public class SampleLoginModule implements LoginModule {
    private String username;
    private String password;

    private SamplePrincipal userPrincipal;

    public boolean login() throws LoginException {
        //Here i check the credentials 
    }

    public boolean commit() throws LoginException {
        //Here i add principal to subject 

        userPrincipal.setName("username");

        if (!(subject.getPrincipals().contains(userPrincipal))) 
            subject.getPrincipals().add(userPrincipal);
        }
    }
}

MySimplePrincipal

public class SamplePrincipal implements Principal {
    private String name;

    public SamplePrincipal() {
        super();
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }   
}

我会在方法提交中向主体添加一个角色,因为isUserInRole否则返回false

我该怎么做?

1 个答案:

答案 0 :(得分:1)

添加一个名为Roles的java.security.acl.Group,其中包含用户的角色名称:

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

Group roleGroup = new JAASGroup("Roles");
for (String role : userRoles)
  roleGroup.addMember(new RolePrincipal(role));

// group principal
principals.add(roleGroup);

// username principal
principals.add(new UserPrincipal("user"));

其中JAASGroup是java.security.acl.Group的实现,RolePrincipal和UserPrincipal是java.security.Principal的实现。