How to add LDAP cache in Spring LDAP?

后端 未结 2 1753
臣服心动
臣服心动 2021-01-12 10:29

I want to cache LDAP user data locally to allow faster queries. Do the Spring LDAP offers such a functionality? How can I do this?

I am using Spring Security 3.1 and

相关标签:
2条回答
  • 2021-01-12 11:03

    If you configure EhCacheBasedUserCache and use ldap-user-service then you can use cache as:

        <authentication-manager>
       <authentication-provider>
        <ldap-user-service 
           user-search-filter="(sAMAccountName={0})" user-search-base="dc=myDomain,dc=com" cache-ref="userCache" />
       </authentication-provider>
    </authentication-manager>
    
    0 讨论(0)
  • 2021-01-12 11:09

    I don't think Spring offers client side LDAP caching out of the box, as caching LDAP query results on the client would pose a security risk. The cache will certainly hold stale data at some point, which is not a huge problem if it's e.g. the email/home address of the user, but much worse when it comes to e.g. role assignments and other authentication/authorization related data. You will be much better off by scaling up the server side, so that it's able to handle the load.

    That's being said, introducing caching is pretty easy since Spring 3.1, because it provides excellent support for it. In your case it would be enough to use a custom LdapContextSource like the following:

    public class CachingLdapContextSource extends AbstractContextSource {
    
        @Override
        protected DirContext getDirContextInstance(Hashtable environment) 
            throws NamingException 
        {
            InitialLdapContext context = new InitialLdapContext(environment, null);
            return new CachingDirContextWrapper(context);
        }
    }
    

    The wrapper class simply delegates all DirContext methods to the underlying implementation and decorates methods to be cached with @Cacheable.

    class CachingDirContextWrapper implements DirContext {
    
        private final DirContext delegate;
    
        CachingDirContextWrapper(DirContext delegate) {
            this.delegate = delegate;
        }
    
        @Override
        @Cacheable(value = "search")
        public NamingEnumeration<SearchResult> search(...)
        {
            return delegate.search(name, matchingAttributes, attributesToReturn);
        }
    
        ...
    }
    

    Refer to the official documentation, and this tutorial on details about how to configure a cache storage to be used by Spring.

    But once again, you'd better not do this, I think.

    0 讨论(0)
提交回复
热议问题