1 18 package sync4j.framework.security.jaas; 19 20 import java.io.*; 21 import java.util.logging.Logger ; 22 import java.util.logging.Level ; 23 24 import javax.security.auth.callback.*; 25 26 import sync4j.framework.core.Cred; 27 import sync4j.framework.logging.Sync4jLogger; 28 import sync4j.framework.tools.Base64; 29 import org.apache.commons.lang.StringUtils; 30 31 42 public class CredentialHandler implements CallbackHandler { 43 44 46 public static final String SUPPORTED_TYPES = Cred.AUTH_TYPE_BASIC; 47 48 50 private String login = null; 51 private char[] password = null; 52 53 55 protected final Logger log = Sync4jLogger.getLogger(); 56 57 59 66 public CredentialHandler(Cred credential) throws IllegalArgumentException { 67 68 String type = credential.getType(); 69 70 if (log.isLoggable(Level.FINEST)) { 71 log.finest("credential: " + credential); 72 } 73 74 if (SUPPORTED_TYPES.indexOf(type) < 0) { 75 throw new IllegalArgumentException ( "Authorization type '" 76 + type 77 + "' not supported" 78 ); 79 } 80 81 if (Cred.AUTH_TYPE_BASIC.equals(type)) { 82 String s = new String (Base64.decode(credential.getData())); 83 84 int p = s.indexOf(':'); 85 86 if (p == -1) { 87 login = s; 88 password = null; 89 } else { 90 login = (p>0) ? s.substring(0, p) : ""; 91 password = toChars((p == (s.length()-1)) ? "" : s.substring(p+1)); 92 } 93 } 94 } 95 96 98 103 public String getLogin() { 104 return login; 105 } 106 107 109 public void handle(Callback[] callbacks) 110 throws IOException, UnsupportedCallbackException { 111 for (int i = 0; i < callbacks.length; i++) { 112 if (log.isLoggable(Level.FINEST)) { 113 log.finest("Handling " + callbacks[i]); 114 } 115 116 if (callbacks[i] instanceof TextOutputCallback) { 117 118 TextOutputCallback toc = (TextOutputCallback)callbacks[i]; 120 switch (toc.getMessageType()) { 121 case TextOutputCallback.INFORMATION: 122 log.info(toc.getMessage()); 123 break; 124 case TextOutputCallback.ERROR: 125 log.severe(toc.getMessage()); 126 break; 127 case TextOutputCallback.WARNING: 128 log.warning(toc.getMessage()); 129 break; 130 default: 131 throw new IOException( "Unsupported message type: " 132 + toc.getMessageType() 133 ); 134 } 135 136 } else if (callbacks[i] instanceof NameCallback) { 137 NameCallback nc = (NameCallback)callbacks[i]; 138 nc.setName(login); 139 } else if (callbacks[i] instanceof PasswordCallback) { 140 PasswordCallback nc = (PasswordCallback)callbacks[i]; 141 nc.setPassword(password); 142 } else { 143 throw new UnsupportedCallbackException 144 (callbacks[i], "Unrecognized Callback"); 145 } 146 } 147 } 148 149 151 private char[] toChars(String str) { 152 if (StringUtils.isEmpty(str)) { 153 return new char[0]; 154 } 155 156 int l = str.length(); 157 char[] ret = new char[l]; 158 159 str.getChars(0, l, ret, 0); 160 161 return ret; 162 } 163 } | Popular Tags |