1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.ws.security.validate;
21
22 import javax.security.auth.Subject;
23 import javax.security.auth.callback.CallbackHandler;
24 import javax.security.auth.login.LoginContext;
25 import javax.security.auth.login.LoginException;
26
27 import org.apache.ws.security.NamePasswordCallbackHandler;
28 import org.apache.ws.security.WSConstants;
29 import org.apache.ws.security.WSSecurityException;
30 import org.apache.ws.security.handler.RequestData;
31 import org.apache.ws.security.message.token.UsernameToken;
32
33
34
35
36
37
38
39 public class JAASUsernameTokenValidator implements Validator {
40
41 private static org.apache.commons.logging.Log log =
42 org.apache.commons.logging.LogFactory.getLog(JAASUsernameTokenValidator.class);
43
44 private String contextName = null;
45
46 public void setContextName(String name) {
47 contextName = name;
48 }
49
50 public String getContextName() {
51 return contextName;
52 }
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68 public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
69 if (credential == null || credential.getUsernametoken() == null) {
70 throw new WSSecurityException(WSSecurityException.FAILURE, "noCredential");
71 }
72
73 String user = null;
74 String password = null;
75
76 UsernameToken usernameToken = credential.getUsernametoken();
77
78 user = usernameToken.getName();
79 String pwType = usernameToken.getPasswordType();
80 if (log.isDebugEnabled()) {
81 log.debug("UsernameToken user " + usernameToken.getName());
82 log.debug("UsernameToken password type " + pwType);
83 }
84
85 if (usernameToken.isHashed()) {
86 log.warn("Authentication failed as hashed username token not supported");
87 throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION);
88 }
89
90 password = usernameToken.getPassword();
91
92 if (!WSConstants.PASSWORD_TEXT.equals(pwType)) {
93 log.warn("Password type " + pwType + " not supported");
94 throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION);
95 }
96
97 if (!(user != null && user.length() > 0 && password != null && password.length() > 0)) {
98 log.warn("User or password empty");
99 throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION);
100 }
101
102 try {
103 CallbackHandler handler = getCallbackHandler(user, password);
104 LoginContext ctx = new LoginContext(getContextName(), handler);
105 ctx.login();
106 Subject subject = ctx.getSubject();
107 credential.setSubject(subject);
108
109 } catch (LoginException ex) {
110 log.info("Authentication failed", ex);
111 throw new WSSecurityException(
112 WSSecurityException.FAILED_AUTHENTICATION, null, null, ex
113 );
114 }
115
116 return credential;
117
118 }
119
120 protected CallbackHandler getCallbackHandler(String name, String password) {
121 return new NamePasswordCallbackHandler(name, password);
122 }
123
124 }