View Javadoc

1   /*
2    * Copyright 2008 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springframework.ws.soap.security.xwss.callback;
18  
19  import java.io.IOException;
20  import javax.security.auth.callback.Callback;
21  import javax.security.auth.callback.UnsupportedCallbackException;
22  
23  import com.sun.xml.wss.impl.callback.PasswordValidationCallback;
24  import com.sun.xml.wss.impl.callback.TimestampValidationCallback;
25  
26  import org.springframework.beans.factory.InitializingBean;
27  import org.springframework.dao.DataAccessException;
28  import org.springframework.security.context.SecurityContextHolder;
29  import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
30  import org.springframework.security.providers.dao.UserCache;
31  import org.springframework.security.providers.dao.cache.NullUserCache;
32  import org.springframework.security.userdetails.UserDetails;
33  import org.springframework.security.userdetails.UserDetailsService;
34  import org.springframework.security.userdetails.UsernameNotFoundException;
35  import org.springframework.util.Assert;
36  import org.springframework.ws.soap.security.callback.AbstractCallbackHandler;
37  import org.springframework.ws.soap.security.callback.CleanupCallback;
38  import org.springframework.ws.soap.security.support.SpringSecurityUtils;
39  
40  /**
41   * Callback handler that validates a password digest using an Spring Security <code>UserDetailsService</code>. Logic
42   * based on Spring Security's <code>DigestProcessingFilter</code>.
43   * <p/>
44   * An Spring Security <code>UserDetailService</code> is used to load <code>UserDetails</code> from. The digest of the
45   * password contained in this details object is then compared with the digest in the message.
46   * <p/>
47   * This class only handles <code>PasswordValidationCallback</code>s that contain a <code>DigestPasswordRequest</code>,
48   * and throws an <code>UnsupportedCallbackException</code> for others.
49   *
50   * @author Arjen Poutsma
51   * @see org.springframework.security.userdetails.UserDetailsService
52   * @see com.sun.xml.wss.impl.callback.PasswordValidationCallback
53   * @see com.sun.xml.wss.impl.callback.PasswordValidationCallback.DigestPasswordRequest
54   * @see org.springframework.security.ui.digestauth.DigestProcessingFilter
55   * @since 1.5.0
56   */
57  public class SpringDigestPasswordValidationCallbackHandler extends AbstractCallbackHandler implements InitializingBean {
58  
59      private UserCache userCache = new NullUserCache();
60  
61      private UserDetailsService userDetailsService;
62  
63      /** Sets the users cache. Not required, but can benefit performance. */
64      public void setUserCache(UserCache userCache) {
65          this.userCache = userCache;
66      }
67  
68      /** Sets the Spring Security user details service. Required. */
69      public void setUserDetailsService(UserDetailsService userDetailsService) {
70          this.userDetailsService = userDetailsService;
71      }
72  
73      public void afterPropertiesSet() throws Exception {
74          Assert.notNull(userDetailsService, "userDetailsService is required");
75      }
76  
77      /**
78       * Handles <code>PasswordValidationCallback</code>s that contain a <code>DigestPasswordRequest</code>, and throws an
79       * <code>UnsupportedCallbackException</code> for others
80       *
81       * @throws javax.security.auth.callback.UnsupportedCallbackException
82       *          when the callback is not supported
83       */
84      protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException {
85          if (callback instanceof PasswordValidationCallback) {
86              PasswordValidationCallback passwordCallback = (PasswordValidationCallback) callback;
87              if (passwordCallback.getRequest() instanceof PasswordValidationCallback.DigestPasswordRequest) {
88                  PasswordValidationCallback.DigestPasswordRequest request =
89                          (PasswordValidationCallback.DigestPasswordRequest) passwordCallback.getRequest();
90                  String username = request.getUsername();
91                  UserDetails user = loadUserDetails(username);
92                  if (user != null) {
93                      SpringSecurityUtils.checkUserValidity(user);
94                      request.setPassword(user.getPassword());
95                  }
96                  SpringSecurityDigestPasswordValidator validator = new SpringSecurityDigestPasswordValidator(user);
97                  passwordCallback.setValidator(validator);
98                  return;
99              }
100         }
101         else if (callback instanceof TimestampValidationCallback) {
102             TimestampValidationCallback timestampCallback = (TimestampValidationCallback) callback;
103             timestampCallback.setValidator(new DefaultTimestampValidator());
104 
105         }
106         else if (callback instanceof CleanupCallback) {
107             SecurityContextHolder.clearContext();
108             return;
109         }
110         throw new UnsupportedCallbackException(callback);
111     }
112 
113     private UserDetails loadUserDetails(String username) throws DataAccessException {
114         UserDetails user = userCache.getUserFromCache(username);
115 
116         if (user == null) {
117             try {
118                 user = userDetailsService.loadUserByUsername(username);
119             }
120             catch (UsernameNotFoundException notFound) {
121                 if (logger.isDebugEnabled()) {
122                     logger.debug("Username '" + username + "' not found");
123                 }
124                 return null;
125             }
126             userCache.putUserInCache(user);
127         }
128         return user;
129     }
130 
131     private class SpringSecurityDigestPasswordValidator extends PasswordValidationCallback.DigestPasswordValidator {
132 
133         private UserDetails user;
134 
135         private SpringSecurityDigestPasswordValidator(UserDetails user) {
136             this.user = user;
137         }
138 
139         public boolean validate(PasswordValidationCallback.Request request)
140                 throws PasswordValidationCallback.PasswordValidationException {
141             if (super.validate(request)) {
142                 UsernamePasswordAuthenticationToken authRequest =
143                         new UsernamePasswordAuthenticationToken(user, user.getPassword());
144                 if (logger.isDebugEnabled()) {
145                     logger.debug("Authentication success: " + authRequest.toString());
146                 }
147 
148                 SecurityContextHolder.getContext().setAuthentication(authRequest);
149                 return true;
150             }
151             else {
152                 return false;
153             }
154         }
155     }
156 
157 }