datahub/datahub-frontend/app/security/AuthenticationManager.java

69 lines
2.5 KiB
Java
Raw Normal View History

2015-11-19 14:39:21 -08:00
package security;
2018-07-31 13:22:18 -07:00
import com.google.common.base.Preconditions;
import java.util.Collections;
2019-08-31 20:51:14 -07:00
import javax.annotation.Nonnull;
import javax.naming.AuthenticationException;
2019-08-31 20:51:14 -07:00
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
2018-07-27 16:33:52 -07:00
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.jaas.JAASLoginService;
import org.eclipse.jetty.jaas.PropertyUserStoreManager;
import play.Logger;
2015-11-19 14:39:21 -08:00
public class AuthenticationManager {
private AuthenticationManager(boolean verbose) {}
2019-08-31 20:51:14 -07:00
public static void authenticateJaasUser(@Nonnull String userName, @Nonnull String password)
throws Exception {
2019-08-31 20:51:14 -07:00
Preconditions.checkArgument(!StringUtils.isAnyEmpty(userName), "Username cannot be empty");
JAASLoginService jaasLoginService = new JAASLoginService("WHZ-Authentication");
PropertyUserStoreManager propertyUserStoreManager = new PropertyUserStoreManager();
propertyUserStoreManager.start();
jaasLoginService.setBeans(Collections.singletonList(propertyUserStoreManager));
JAASLoginService.INSTANCE.set(jaasLoginService);
2018-07-27 16:33:52 -07:00
try {
LoginContext lc =
new LoginContext("WHZ-Authentication", new WHZCallbackHandler(userName, password));
2018-07-27 16:33:52 -07:00
lc.login();
} catch (LoginException le) {
AuthenticationException authenticationException =
new AuthenticationException(le.getMessage());
authenticationException.setRootCause(le);
throw authenticationException;
}
}
2018-07-30 15:39:24 -07:00
private static class WHZCallbackHandler implements CallbackHandler {
private String password;
private String username;
2019-08-31 20:51:14 -07:00
private WHZCallbackHandler(@Nonnull String username, @Nonnull String password) {
2018-07-27 16:33:52 -07:00
this.username = username;
this.password = password;
}
2018-07-31 10:10:52 -07:00
@Override
2019-08-31 20:51:14 -07:00
public void handle(@Nonnull Callback[] callbacks) {
2018-07-27 16:33:52 -07:00
NameCallback nc = null;
PasswordCallback pc = null;
for (Callback callback : callbacks) {
Logger.debug(
"The submitted callback is of type: " + callback.getClass() + " : " + callback);
2018-07-27 16:33:52 -07:00
if (callback instanceof NameCallback) {
nc = (NameCallback) callback;
nc.setName(this.username);
} else if (callback instanceof PasswordCallback) {
pc = (PasswordCallback) callback;
pc.setPassword(this.password.toCharArray());
}
}
}
}
}