问题
I am stuck possibly at a very stupid question, trying to implement LDAP role based authentication/authorization in a Grails application (bookstore) using spring-security-core and spring-security-ldap plugins. I created a custom UserDetailsContextMapper and trying to map my LDAP role with application role. However, the memberof attribute is never returned in the attributes.
UserDetails mapUserFromContext(DirContextOperations ctx, String username,
Collection authorities) {
Attributes attributes = ctx.getAttributes();
Object[] groups = new Object[10];
groups = ctx.getObjectAttributes("memberof"); //returns empty array
Set<GrantedAuthority> authority = new HashSet<GrantedAuthority>();
for(Object group: groups){
if (group.toString().toLowerCase().contains("ROLE_FROM_LDAP".toLowerCase()) == true){
authority.add(new SimpleGrantedAuthority("ROLE_APP"));
break;
}
}
User userDetails = new User(username, "", false, false, false, false, authority);
return userDetails;
}
Interestingly, when I run a query on LDAP using ldapsearch, I do get the attribute returned.
What I am stuck at is how to configure the equivalent of "requesting:" (as shown below with ldapsearch) in the Grails LDAP configuration so that the plugin is able to fetch the "memberof" attribute (I tried adding that to Grails LDAP plugin configuration with ldap.search.attributesToReturn but to no avail).
ldapsearch -t -x -b "ou=people,dc=domain,dc=com" "cn=myusername" memberof
.....
# LDAPv3
# base <ou=people,dc=domain,dc=com> with scope subtree
# filter: cn=myusername
# requesting: memberof
#
.....
dn: cn=myusername,ou=people,dc=domain,dc=com
memberOf: cn=ROLE_FROM_LDAP,ou=groups,dc=domain,dc=com
Following is the Grails LDAP configuration:
grails {
plugin {
springsecurity {
providerNames: ['ldapAuthProvider', 'anonymousAuthenticationProvider']
ldap {
useRememberMe = false
context {
managerDn = 'cn=manager,dc=domain,dc=com'
managerPassword = 'secret'
server = 'ldap://localhost:389/'
}
search {
base = 'ou=people,dc=domain,dc=com'
filter = 'cn={0}'
searchSubtree = true
attributesToReturn: ['memberOf'] //extra attributes you want returned
}
auth {
hideUserNotFoundExceptions = false
}
authorities {
retrieveDatabaseRoles = false
retrieveGroupRoles = true
groupSearchBase = 'ou=groups,dc=domain,dc=com'
groupSearchFilter = 'member={0}'
}
}
}
}
}
回答1:
You can inject springSecurityService and fetch like:
springSecurityService.getPrincipal().getAuthorities()
来源:https://stackoverflow.com/questions/43316029/fetching-ldap-attribute-memberof-inside-grails-spring-application