View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.module.jaas;
8   
9   import org.mule.api.security.Authentication;
10  
11  import java.io.IOException;
12  
13  import javax.security.auth.callback.Callback;
14  import javax.security.auth.callback.CallbackHandler;
15  import javax.security.auth.callback.NameCallback;
16  import javax.security.auth.callback.PasswordCallback;
17  import javax.security.auth.callback.UnsupportedCallbackException;
18  
19  public class MuleCallbackHandler implements CallbackHandler
20  {
21      private Authentication authentication;
22      private String username;
23      private String password;
24  
25      /**
26       * @param authentication
27       */
28      public MuleCallbackHandler(Authentication authentication)
29      {
30          this.authentication = authentication;
31          this.username = (String) this.authentication.getPrincipal();
32          this.password = (String) this.authentication.getCredentials();
33      }
34  
35      /**
36       * The handle() method handles the callbacks to be passed to the Jaas security.
37       * It makes use of two types of callbacks: the NameCallback and the
38       * PasswordCallback.
39       * 
40       * @param callbacks
41       * @throws IOException
42       * @throws UnsupportedCallbackException
43       */
44      public final void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException
45      {
46          for (int i = 0; i < callbacks.length; i++)
47          {
48              if (callbacks[i] instanceof NameCallback)
49              {
50                  NameCallback nameCb = (NameCallback) callbacks[i];
51                  nameCb.setName(username);
52              }
53              else if (callbacks[i] instanceof PasswordCallback)
54              {
55                  PasswordCallback passCb = (PasswordCallback) callbacks[i];
56                  passCb.setPassword(password.toCharArray());
57              }
58              else
59              {
60                  throw (new UnsupportedCallbackException(callbacks[i], "Callback class not supported"));
61              }
62          }
63      }
64  }