1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.acegisecurity.providers.x509.cache;
17
18 import net.sf.ehcache.CacheException;
19 import net.sf.ehcache.Element;
20 import net.sf.ehcache.Ehcache;
21
22 import org.acegisecurity.providers.x509.X509UserCache;
23
24 import org.acegisecurity.userdetails.UserDetails;
25
26 import org.apache.commons.logging.Log;
27 import org.apache.commons.logging.LogFactory;
28
29 import org.springframework.beans.factory.InitializingBean;
30
31 import org.springframework.dao.DataRetrievalFailureException;
32
33 import org.springframework.util.Assert;
34
35 import java.security.cert.X509Certificate;
36
37
38
39
40
41
42
43
44
45
46 public class EhCacheBasedX509UserCache implements X509UserCache, InitializingBean {
47
48
49 private static final Log logger = LogFactory.getLog(EhCacheBasedX509UserCache.class);
50
51
52
53 private Ehcache cache;
54
55
56
57 public void afterPropertiesSet() throws Exception {
58 Assert.notNull(cache, "cache is mandatory");
59 }
60
61 public UserDetails getUserFromCache(X509Certificate userCert) {
62 Element element = null;
63
64 try {
65 element = cache.get(userCert);
66 } catch (CacheException cacheException) {
67 throw new DataRetrievalFailureException("Cache failure: " + cacheException.getMessage());
68 }
69
70 if (logger.isDebugEnabled()) {
71 String subjectDN = "unknown";
72
73 if ((userCert != null) && (userCert.getSubjectDN() != null)) {
74 subjectDN = userCert.getSubjectDN().toString();
75 }
76
77 logger.debug("X.509 Cache hit. SubjectDN: " + subjectDN);
78 }
79
80 if (element == null) {
81 return null;
82 } else {
83 return (UserDetails) element.getValue();
84 }
85 }
86
87 public void putUserInCache(X509Certificate userCert, UserDetails user) {
88 Element element = new Element(userCert, user);
89
90 if (logger.isDebugEnabled()) {
91 logger.debug("Cache put: " + userCert.getSubjectDN());
92 }
93
94 cache.put(element);
95 }
96
97 public void removeUserFromCache(X509Certificate userCert) {
98 if (logger.isDebugEnabled()) {
99 logger.debug("Cache remove: " + userCert.getSubjectDN());
100 }
101
102 cache.remove(userCert);
103 }
104
105 public void setCache(Ehcache cache) {
106 this.cache = cache;
107 }
108 }