简体   繁体   中英

isUserInRole sometimes returns false

I'm developing my first Jsf, Jaas, JPA, JBoss application and now I have this trouble. I created two security domains in 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>

If I use "Database" domain everything works, while if I use a "Custom" domain I can not set the role to the principal.

My 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;
    }   
}

I would add a role to a principal within of the method commit because isUserInRole otherwise return false .

How can I do this?

Add a java.security.acl.Group named Roles that contains the role names of your user :

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"));

where JAASGroup is an implementation of java.security.acl.Group and RolePrincipal and UserPrincipal are implementations of java.security.Principal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM