简体   繁体   中英

How to Map AD Groups to User Role Spring Security LDAP

I have a web application built using Java Spring MVC.

I'm just setting up spring security connecting to an LDAP server for authentication.

I've successfully set it up so that I am able to login to my application but I can't find anything to help me in mapping an AD group to a user role within Java as I can only get a 403 forbidden page ie I've been authenticated but don't have permissions yet.

I currently have:

<http auto-config="true">
    <intercept-url pattern="/**" access="ROLE_USER" />      
</http>

<ldap-server id="ldapServer" url="LDAPURL" manager-dn="USER" manager-password="PASSWORD"  />

<authentication-manager > 
    <ldap-authentication-provider           
        group-search-base="OU=GROUPS"
        group-search-filter="sAMAccountName={0}"

        user-search-base="OU=USERS"
        user-search-filter="sAMAccountName={0}" 

        />
</authentication-manager>

Say that user was a part of the AD group g-group-UK-user I then want to be able to map that AD group to ROLE_USER so that user can then see the whole web app.

I can only seem to find very simple examples where the groups are either ADMIN or USER in which case the prefix ROLE is just added to the group or the other method seems to be using UserDetailContextMapper but I can't find a clear use of this.

To do this I used the following within authentication manager:

user-context-mapper-ref="customUserContextMapper"

I then used the following class to check if that user belongs to a certain AD group and then assign the ROLE_USER role to their authorities:

@Override
public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<? extends GrantedAuthority> authorities) 
{

    Attributes attributes = ctx.getAttributes();
    Object[] groups = new Object[100];
    groups = ctx.getObjectAttributes("memberOf");

    LOGGER.debug("Attributes: {}", attributes);

    Set<GrantedAuthority> authority = new HashSet<GrantedAuthority>();

    for(Object group: groups)
    {

        if (group.toString().toLowerCase().contains("AD_GROUP_NAME".toLowerCase()) == true)
        {
            authority.add(new SimpleGrantedAuthority("ROLE_USER"));
            break;          
        }
    }

    User userDetails = new User(username, "", false, false, false, false, authority);
    return userDetails;
}

Please note that the class is a little more complicated than usual because of the LDAP server I was connecting which has a different structure than usual in that the groups a user has access to are stored in an attribute under the user and not the other way round in which a group would have as an attribute all the users that belong to it.

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