1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package net.sf.ldaptemplate.support.acegi;
18
19 import org.acegisecurity.Authentication;
20 import org.acegisecurity.context.SecurityContextHolder;
21 import org.acegisecurity.userdetails.ldap.LdapUserDetails;
22 import org.apache.commons.logging.Log;
23 import org.apache.commons.logging.LogFactory;
24
25 import net.sf.ldaptemplate.AuthenticationSource;
26
27 /***
28 * An AuthenticationSource to retrieve authentication information stored in
29 * Acegi's SecurityContextHolder. Use Acegi's LdapAuthenticationProvider have a
30 * LdapUserDetails object placed in the authentication.
31 *
32 * @author Mattias Arthursson
33 *
34 */
35 public class AcegiAuthenticationSource implements AuthenticationSource {
36 private static final Log log = LogFactory
37 .getLog(AcegiAuthenticationSource.class);
38
39 /***
40 * Get the principals of the logged in user, in this case the distinguished
41 * name.
42 *
43 * @return the distinguished name of the logged in user.
44 */
45 public String getPrincipal() {
46 Authentication authentication = SecurityContextHolder.getContext()
47 .getAuthentication();
48 if (authentication != null) {
49 Object principal = authentication.getPrincipal();
50 if (!(principal instanceof LdapUserDetails)) {
51 throw new IllegalArgumentException(
52 "The principal property of the authentication object -"
53 + "needs to be a LdapUserDetails.");
54 } else {
55 LdapUserDetails details = (LdapUserDetails) principal;
56 return details.getDn();
57 }
58 } else {
59 log.warn("No Authentication object set in SecurityContext - "
60 + "returning empty String as Principal");
61 return "";
62 }
63 }
64
65
66
67
68 public String getCredentials() {
69 Authentication authentication = SecurityContextHolder.getContext()
70 .getAuthentication();
71
72 if (authentication != null) {
73 return (String) authentication.getCredentials();
74 } else {
75 log.warn("No Authentication object set in SecurityContext - "
76 + "returning empty String as Credentials");
77 return "";
78 }
79 }
80
81 }