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

72 lines
2.5 KiB
Java
Raw Normal View History

2015-11-19 14:39:21 -08:00
/**
* Copyright 2015 LinkedIn Corp. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package security;
2018-07-27 16:33:52 -07:00
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
2015-11-19 14:39:21 -08:00
import javax.naming.AuthenticationException;
2015-11-19 14:39:21 -08:00
import javax.naming.NamingException;
2018-07-27 16:33:52 -07:00
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.Callback;
2015-11-19 14:39:21 -08:00
public class AuthenticationManager {
public static void authenticateUser(String userName, String password) throws NamingException {
if (userName == null || userName.isEmpty() || password == null || password.isEmpty()) {
throw new IllegalArgumentException("Username and password can not be blank.");
}
2018-07-27 16:33:52 -07:00
LoginContext lc = null;
try {
2018-07-30 15:39:24 -07:00
lc = new LoginContext("WHZ-Authentication", new WHZCallbackHandler(userName, password));
2018-07-27 16:33:52 -07:00
} catch (LoginException le) {
throw new AuthenticationException(le.toString());
2015-11-19 14:39:21 -08:00
}
2018-07-27 16:33:52 -07:00
try {
lc.login();
} catch (LoginException le) {
throw new AuthenticationException(le.toString());
}
}
2018-07-30 15:39:24 -07:00
private static class WHZCallbackHandler implements CallbackHandler {
2018-07-27 16:33:52 -07:00
private String password = null;
private String username = null;
2018-07-30 15:39:24 -07:00
private WHZCallbackHandler(String username, String password) {
2018-07-27 16:33:52 -07:00
this.username = username;
this.password = password;
}
2018-07-27 16:33:52 -07:00
public void handle(Callback[] callbacks)
throws UnsupportedCallbackException {
NameCallback nc = null;
PasswordCallback pc = null;
for (Callback callback : callbacks) {
if (callback instanceof NameCallback) {
nc = (NameCallback) callback;
nc.setName(this.username);
} else if (callback instanceof PasswordCallback) {
pc = (PasswordCallback) callback;
pc.setPassword(this.password.toCharArray());
} else {
throw new UnsupportedCallbackException(callback, "The submitted Callback is unsupported");
}
}
}
}
}