1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package ch.elca.el4j.services.security.authentication;
18
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
21 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
22 import org.springframework.security.core.Authentication;
23 import org.springframework.security.core.context.SecurityContextHolder;
24
25 import ch.elca.el4j.services.security.encryption.AESCipher;
26
27
28
29
30
31
32
33
34
35 public class SecureUsernamePasswordAuthenticationServiceContextPasser extends
36 AuthenticationServiceContextPasser {
37
38
39
40
41 private static Logger s_logger = LoggerFactory.getLogger(SecureUsernamePasswordAuthenticationServiceContextPasser.class);
42
43
44
45
46 private AESCipher m_cipher;
47
48
49
50
51 public void setKey(String key) {
52 m_cipher = new AESCipher(key);
53 }
54
55
56 @Override
57 public Object getImplicitlyPassedContext() {
58 Authentication auth = SecurityContextHolder.getContext().getAuthentication();
59 if (auth instanceof UsernamePasswordAuthenticationToken) {
60 UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(
61 auth.getPrincipal(), m_cipher.encrypt((String) auth.getCredentials()), auth.getAuthorities());
62
63 return result;
64 } else {
65 return auth;
66 }
67 }
68
69
70 @Override
71 public void pushImplicitlyPassedContext(Object context) {
72 if (context == null) {
73 s_logger.warn("Authentication == null");
74 SecurityContextHolder.getContext().setAuthentication(null);
75 return;
76 }
77
78 Authentication auth = (Authentication) context;
79 if (auth instanceof UsernamePasswordAuthenticationToken) {
80 UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(
81 auth.getPrincipal(), m_cipher.decrypt((String) auth.getCredentials()));
82
83 SecurityContextHolder.getContext().setAuthentication(result);
84 } else {
85
86 SecurityContextHolder.getContext().setAuthentication(auth);
87 }
88 }
89
90
91 }