use of com.gitblit.auth.AuthenticationProvider in project gitblit by gitblit.
the class AuthenticationManager method start.
@Override
public AuthenticationManager start() {
// automatically adjust legacy configurations
String realm = settings.getString(Keys.realm.userService, "${baseFolder}/users.conf");
if (legacyRedirects.containsKey(realm)) {
logger.warn("");
logger.warn(Constants.BORDER2);
logger.warn(" IUserService '{}' is obsolete!", realm);
logger.warn(" Please set '{}={}'", "realm.authenticationProviders", legacyRedirects.get(realm));
logger.warn(Constants.BORDER2);
logger.warn("");
// conditionally override specified authentication providers
if (StringUtils.isEmpty(settings.getString(Keys.realm.authenticationProviders, null))) {
settings.overrideSetting(Keys.realm.authenticationProviders, legacyRedirects.get(realm));
}
}
// instantiate and setup specified authentication providers
List<String> providers = settings.getStrings(Keys.realm.authenticationProviders);
if (providers.isEmpty()) {
logger.info("External authentication disabled.");
} else {
for (String provider : providers) {
try {
Class<?> authClass;
if (providerNames.containsKey(provider)) {
// map the name -> class
authClass = providerNames.get(provider);
} else {
// reflective lookup
authClass = Class.forName(provider);
}
logger.info("setting up {}", authClass.getName());
AuthenticationProvider authImpl = (AuthenticationProvider) authClass.newInstance();
authImpl.setup(runtimeManager, userManager);
authenticationProviders.add(authImpl);
} catch (Exception e) {
logger.error("", e);
}
}
}
return this;
}
use of com.gitblit.auth.AuthenticationProvider in project gitblit by gitblit.
the class AuthenticationManager method authenticate.
/**
* Authenticate a user based on HTTP request parameters.
*
* Authentication by custom HTTP header, servlet container principal, X509Certificate, cookie,
* and finally BASIC header.
*
* @param httpRequest
* @param requiresCertificate
* @return a user object or null
*/
@Override
public UserModel authenticate(HttpServletRequest httpRequest, boolean requiresCertificate) {
// Check if this request has already been authenticated, and trust that instead of re-processing
String reqAuthUser = (String) httpRequest.getAttribute(Constants.ATTRIB_AUTHUSER);
if (!StringUtils.isEmpty(reqAuthUser)) {
logger.debug("Called servlet authenticate when request is already authenticated.");
return userManager.getUserModel(reqAuthUser);
}
// try to authenticate by servlet container principal
if (!requiresCertificate) {
Principal principal = httpRequest.getUserPrincipal();
if (principal != null) {
String username = principal.getName();
if (!StringUtils.isEmpty(username)) {
boolean internalAccount = userManager.isInternalAccount(username);
UserModel user = userManager.getUserModel(username);
if (user != null) {
// existing user
flagRequest(httpRequest, AuthenticationType.CONTAINER, user.username);
logger.debug(MessageFormat.format("{0} authenticated by servlet container principal from {1}", user.username, httpRequest.getRemoteAddr()));
return validateAuthentication(user, AuthenticationType.CONTAINER);
} else if (settings.getBoolean(Keys.realm.container.autoCreateAccounts, false) && !internalAccount) {
// auto-create user from an authenticated container principal
user = new UserModel(username.toLowerCase());
user.displayName = username;
user.password = Constants.EXTERNAL_ACCOUNT;
user.accountType = AccountType.CONTAINER;
// Try to extract user's informations for the session
// it uses "realm.container.autoAccounts.*" as the attribute name to look for
HttpSession session = httpRequest.getSession();
String emailAddress = resolveAttribute(session, Keys.realm.container.autoAccounts.emailAddress);
if (emailAddress != null) {
user.emailAddress = emailAddress;
}
String displayName = resolveAttribute(session, Keys.realm.container.autoAccounts.displayName);
if (displayName != null) {
user.displayName = displayName;
}
String userLocale = resolveAttribute(session, Keys.realm.container.autoAccounts.locale);
if (userLocale != null) {
user.getPreferences().setLocale(userLocale);
}
String adminRole = settings.getString(Keys.realm.container.autoAccounts.adminRole, null);
if (adminRole != null && !adminRole.isEmpty()) {
if (httpRequest.isUserInRole(adminRole)) {
user.canAdmin = true;
}
}
userManager.updateUserModel(user);
flagRequest(httpRequest, AuthenticationType.CONTAINER, user.username);
logger.debug(MessageFormat.format("{0} authenticated and created by servlet container principal from {1}", user.username, httpRequest.getRemoteAddr()));
return validateAuthentication(user, AuthenticationType.CONTAINER);
} else if (!internalAccount) {
logger.warn(MessageFormat.format("Failed to find UserModel for {0}, attempted servlet container authentication from {1}", principal.getName(), httpRequest.getRemoteAddr()));
}
}
}
}
// try to authenticate by certificate
boolean checkValidity = settings.getBoolean(Keys.git.enforceCertificateValidity, true);
String[] oids = settings.getStrings(Keys.git.certificateUsernameOIDs).toArray(new String[0]);
UserModel model = HttpUtils.getUserModelFromCertificate(httpRequest, checkValidity, oids);
if (model != null) {
// grab real user model and preserve certificate serial number
UserModel user = userManager.getUserModel(model.username);
X509Metadata metadata = HttpUtils.getCertificateMetadata(httpRequest);
if (user != null) {
flagRequest(httpRequest, AuthenticationType.CERTIFICATE, user.username);
logger.debug(MessageFormat.format("{0} authenticated by client certificate {1} from {2}", user.username, metadata.serialNumber, httpRequest.getRemoteAddr()));
return validateAuthentication(user, AuthenticationType.CERTIFICATE);
} else {
logger.warn(MessageFormat.format("Failed to find UserModel for {0}, attempted client certificate ({1}) authentication from {2}", model.username, metadata.serialNumber, httpRequest.getRemoteAddr()));
}
}
if (requiresCertificate) {
// caller requires client certificate authentication (e.g. git servlet)
return null;
}
UserModel user = null;
// try to authenticate by cookie
String cookie = getCookie(httpRequest);
if (!StringUtils.isEmpty(cookie)) {
user = userManager.getUserModel(cookie.toCharArray());
if (user != null) {
flagRequest(httpRequest, AuthenticationType.COOKIE, user.username);
logger.debug(MessageFormat.format("{0} authenticated by cookie from {1}", user.username, httpRequest.getRemoteAddr()));
return validateAuthentication(user, AuthenticationType.COOKIE);
}
}
// try to authenticate by BASIC
final String authorization = httpRequest.getHeader("Authorization");
if (authorization != null && authorization.startsWith("Basic")) {
// Authorization: Basic base64credentials
String base64Credentials = authorization.substring("Basic".length()).trim();
String credentials = new String(Base64.decode(base64Credentials), Charset.forName("UTF-8"));
// credentials = username:password
final String[] values = credentials.split(":", 2);
if (values.length == 2) {
String username = values[0];
char[] password = values[1].toCharArray();
user = authenticate(username, password, httpRequest.getRemoteAddr());
if (user != null) {
flagRequest(httpRequest, AuthenticationType.CREDENTIALS, user.username);
logger.debug(MessageFormat.format("{0} authenticated by BASIC request header from {1}", user.username, httpRequest.getRemoteAddr()));
return validateAuthentication(user, AuthenticationType.CREDENTIALS);
}
}
}
// Check each configured AuthenticationProvider
for (AuthenticationProvider ap : authenticationProviders) {
UserModel authedUser = ap.authenticate(httpRequest);
if (null != authedUser) {
flagRequest(httpRequest, ap.getAuthenticationType(), authedUser.username);
logger.debug(MessageFormat.format("{0} authenticated by {1} from {2} for {3}", authedUser.username, ap.getServiceName(), httpRequest.getRemoteAddr(), httpRequest.getPathInfo()));
return validateAuthentication(authedUser, ap.getAuthenticationType());
}
}
return null;
}
use of com.gitblit.auth.AuthenticationProvider in project gitblit by gitblit.
the class AuthenticationManager method authenticate.
/**
* Authenticate a user based on a username and password.
*
* @see IUserService.authenticate(String, char[])
* @param username
* @param password
* @return a user object or null
*/
@Override
public UserModel authenticate(String username, char[] password, String remoteIP) {
if (StringUtils.isEmpty(username)) {
// can not authenticate empty username
return null;
}
if (username.equalsIgnoreCase(Constants.FEDERATION_USER)) {
// it must be routed to FederationManager
return null;
}
String usernameDecoded = StringUtils.decodeUsername(username);
String pw = new String(password);
if (StringUtils.isEmpty(pw)) {
// can not authenticate empty password
return null;
}
UserModel user = userManager.getUserModel(usernameDecoded);
// try local authentication
if (user != null && user.isLocalAccount()) {
UserModel returnedUser = authenticateLocal(user, password);
if (returnedUser != null) {
// user authenticated
return returnedUser;
}
} else {
// try registered external authentication providers
for (AuthenticationProvider provider : authenticationProviders) {
if (provider instanceof UsernamePasswordAuthenticationProvider) {
UserModel returnedUser = provider.authenticate(usernameDecoded, password);
if (returnedUser != null) {
// user authenticated
returnedUser.accountType = provider.getAccountType();
return validateAuthentication(returnedUser, AuthenticationType.CREDENTIALS);
}
}
}
}
// could not authenticate locally or with a provider
logger.warn(MessageFormat.format("Failed login attempt for {0}, invalid credentials from {1}", username, remoteIP != null ? remoteIP : "unknown"));
return null;
}
Aggregations