001 package org.crsh.auth;
002
003 import org.crsh.plugin.CRaSHPlugin;
004 import org.crsh.plugin.PropertyDescriptor;
005
006 import javax.security.auth.Subject;
007 import javax.security.auth.callback.Callback;
008 import javax.security.auth.callback.CallbackHandler;
009 import javax.security.auth.callback.NameCallback;
010 import javax.security.auth.callback.PasswordCallback;
011 import javax.security.auth.callback.UnsupportedCallbackException;
012 import javax.security.auth.login.LoginContext;
013 import java.io.IOException;
014 import java.util.Collections;
015
016 /**
017 * A jaas plugin for authentication purpose
018 *
019 * @author <a href="mailto:nscavell@redhat.com">Nick Scavelli</a>
020 */
021 public class JaasAuthenticationPlugin extends CRaSHPlugin<AuthenticationPlugin> implements AuthenticationPlugin {
022
023 /** . */
024 static final PropertyDescriptor<String> JAAS_DOMAIN = PropertyDescriptor.create("auth.jaas.domain", (String)null, "The JAAS domain name used for authentication");
025
026 public String getName() {
027 return "jaas";
028 }
029
030 @Override
031 protected Iterable<PropertyDescriptor<?>> createConfigurationCapabilities() {
032 return Collections.<PropertyDescriptor<?>>singletonList(JAAS_DOMAIN);
033 }
034
035 public boolean authenticate(final String username, final String password) throws Exception {
036 String domain = getContext().getProperty(JAAS_DOMAIN);
037 if (domain != null) {
038 log.debug("Will use the JAAS domain '" + domain + "' for authenticating user " + username);
039 LoginContext loginContext = new LoginContext(domain, new Subject(), new CallbackHandler() {
040 public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
041 for (Callback c : callbacks) {
042 if (c instanceof NameCallback) {
043 ((NameCallback)c).setName(username);
044 }
045 else if (c instanceof PasswordCallback) {
046 ((PasswordCallback)c).setPassword(password.toCharArray());
047 }
048 else {
049 throw new UnsupportedCallbackException(c);
050 }
051 }
052 }
053 });
054
055 //
056 try {
057 loginContext.login();
058 loginContext.logout();
059 log.debug("Authenticated user " + username + " against the JAAS domain '" + domain + "'");
060 return true;
061 }
062 catch (Exception e) {
063 if (log.isDebugEnabled()) log.error("Exception when authenticating user " + username + " to JAAS domain '" + domain + "'", e);
064 return false;
065 }
066 }
067 else {
068 log.warn("The JAAS domain property '" + JAAS_DOMAIN.name + "' was not found");
069 return false;
070 }
071 }
072
073 @Override
074 public AuthenticationPlugin getImplementation() {
075 return this;
076 }
077 }