use of com.google.gerrit.server.auth.AuthenticationUnavailableException in project gerrit by GerritCodeReview.
the class LdapRealm method authenticate.
@Override
public AuthRequest authenticate(AuthRequest who) throws AccountException {
if (config.getBoolean("ldap", "localUsernameToLowerCase", false)) {
who.setLocalUser(who.getLocalUser().toLowerCase(Locale.US));
}
final String username = who.getLocalUser();
try {
final DirContext ctx;
if (authConfig.getAuthType() == AuthType.LDAP_BIND) {
ctx = helper.authenticate(username, who.getPassword());
} else {
ctx = helper.open();
}
try {
final Helper.LdapSchema schema = helper.getSchema(ctx);
LdapQuery.Result m;
who.setAuthProvidesAccountActiveStatus(true);
m = helper.findAccount(schema, ctx, username, fetchMemberOfEagerly);
who.setActive(true);
if (authConfig.getAuthType() == AuthType.LDAP && !who.isSkipAuthentication()) {
// We found the user account, but we need to verify
// the password matches it before we can continue.
//
helper.close(helper.authenticate(m.getDN(), who.getPassword()));
}
who.setDisplayName(apply(schema.accountFullName, m));
who.setUserName(apply(schema.accountSshUserName, m));
if (schema.accountEmailAddress != null) {
who.setEmailAddress(apply(schema.accountEmailAddress, m));
} else if (emailExpander.canExpand(username)) {
// If LDAP cannot give us a valid email address for this user
// try expanding it through the older email expander code which
// assumes a user name within a domain.
//
who.setEmailAddress(emailExpander.expand(username));
}
//
if (fetchMemberOfEagerly || mandatoryGroup != null) {
Set<AccountGroup.UUID> groups = helper.queryForGroups(ctx, username, m);
if (mandatoryGroup != null) {
GroupReference mandatoryGroupRef = GroupBackends.findExactSuggestion(groupBackend, mandatoryGroup);
if (mandatoryGroupRef == null) {
throw new AccountException("Could not identify mandatory group: " + mandatoryGroup);
}
if (!groups.contains(mandatoryGroupRef.getUUID())) {
throw new AccountException("Not member of mandatory LDAP group: " + mandatoryGroupRef.getName());
}
}
// Regardless if we enabled fetchMemberOfEagerly, we already have the
// groups and it would be a waste not to cache them.
membershipCache.put(username, groups);
}
return who;
} finally {
helper.close(ctx);
}
} catch (IOException | NamingException e) {
logger.atSevere().withCause(e).log("Cannot query LDAP to authenticate user");
throw new AuthenticationUnavailableException("Cannot query LDAP for account", e);
} catch (LoginException e) {
logger.atSevere().withCause(e).log("Cannot authenticate server via JAAS");
throw new AuthenticationUnavailableException("Cannot query LDAP for account", e);
}
}
use of com.google.gerrit.server.auth.AuthenticationUnavailableException in project gerrit by GerritCodeReview.
the class LdapLoginServlet method doPost.
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
req.setCharacterEncoding(UTF_8.name());
String username = Strings.nullToEmpty(req.getParameter("username")).trim();
String password = Strings.nullToEmpty(req.getParameter("password"));
String remember = Strings.nullToEmpty(req.getParameter("rememberme"));
if (username.isEmpty() || password.isEmpty()) {
sendForm(req, res, "Invalid username or password.");
return;
}
AuthRequest areq = authRequestFactory.createForUser(username);
areq.setPassword(password);
AuthResult ares;
try {
ares = accountManager.authenticate(areq);
} catch (AccountUserNameException e) {
sendForm(req, res, e.getMessage());
return;
} catch (AuthenticationUnavailableException e) {
sendForm(req, res, "Authentication unavailable at this time.");
return;
} catch (AuthenticationFailedException e) {
// This exception is thrown if the user provided wrong credentials, we don't need to log a
// stacktrace for it.
logger.atWarning().log("'%s' failed to sign in: %s", username, e.getMessage());
sendForm(req, res, "Invalid username or password.");
return;
} catch (AccountException e) {
logger.atWarning().withCause(e).log("'%s' failed to sign in", username);
sendForm(req, res, "Authentication failed.");
return;
} catch (RuntimeException e) {
logger.atSevere().withCause(e).log("LDAP authentication failed");
sendForm(req, res, "Authentication unavailable at this time.");
return;
}
StringBuilder dest = new StringBuilder();
dest.append(urlProvider.get(req));
dest.append(LoginUrlToken.getToken(req));
CacheHeaders.setNotCacheable(res);
webSession.get().login(ares, "1".equals(remember));
res.sendRedirect(dest.toString());
}
use of com.google.gerrit.server.auth.AuthenticationUnavailableException in project gerrit by GerritCodeReview.
the class ProjectBasicAuthFilter method verify.
private boolean verify(HttpServletRequest req, Response rsp) throws IOException {
final String hdr = req.getHeader(AUTHORIZATION);
if (hdr == null || !hdr.startsWith(LIT_BASIC)) {
// session cookie instead of basic authentication.
return true;
}
final byte[] decoded = BaseEncoding.base64().decode(hdr.substring(LIT_BASIC.length()));
String usernamePassword = new String(decoded, encoding(req));
int splitPos = usernamePassword.indexOf(':');
if (splitPos < 1) {
rsp.sendError(SC_UNAUTHORIZED);
return false;
}
String username = usernamePassword.substring(0, splitPos);
String password = usernamePassword.substring(splitPos + 1);
if (Strings.isNullOrEmpty(password)) {
rsp.sendError(SC_UNAUTHORIZED);
return false;
}
if (authConfig.isUserNameToLowerCase()) {
username = username.toLowerCase(Locale.US);
}
Optional<AccountState> accountState = accountCache.getByUsername(username).filter(a -> a.account().isActive());
if (!accountState.isPresent()) {
logger.atWarning().log("Authentication failed for %s: account inactive or not provisioned in Gerrit", username);
rsp.sendError(SC_UNAUTHORIZED);
return false;
}
AccountState who = accountState.get();
GitBasicAuthPolicy gitBasicAuthPolicy = authConfig.getGitBasicAuthPolicy();
if (gitBasicAuthPolicy == GitBasicAuthPolicy.HTTP || gitBasicAuthPolicy == GitBasicAuthPolicy.HTTP_LDAP) {
if (passwordVerifier.checkPassword(who.externalIds(), username, password)) {
logger.atFine().log("HTTP:%s %s username/password authentication succeeded", req.getMethod(), req.getRequestURI());
return succeedAuthentication(who, null);
}
}
if (gitBasicAuthPolicy == GitBasicAuthPolicy.HTTP) {
return failAuthentication(rsp, username, req);
}
AuthRequest whoAuth = authRequestFactory.createForUser(username);
whoAuth.setPassword(password);
try {
AuthResult whoAuthResult = accountManager.authenticate(whoAuth);
setUserIdentified(whoAuthResult.getAccountId(), whoAuthResult);
logger.atFine().log("HTTP:%s %s Realm authentication succeeded", req.getMethod(), req.getRequestURI());
return true;
} catch (NoSuchUserException e) {
if (passwordVerifier.checkPassword(who.externalIds(), username, password)) {
return succeedAuthentication(who, null);
}
logger.atWarning().withCause(e).log("%s", authenticationFailedMsg(username, req));
rsp.sendError(SC_UNAUTHORIZED);
return false;
} catch (AuthenticationFailedException e) {
// This exception is thrown if the user provided wrong credentials, we don't need to log a
// stacktrace for it.
logger.atWarning().log(authenticationFailedMsg(username, req) + ": %s", e.getMessage());
rsp.sendError(SC_UNAUTHORIZED);
return false;
} catch (AuthenticationUnavailableException e) {
logger.atSevere().withCause(e).log("could not reach authentication backend");
rsp.sendError(SC_SERVICE_UNAVAILABLE);
return false;
} catch (AccountException e) {
logger.atWarning().withCause(e).log("%s", authenticationFailedMsg(username, req));
rsp.sendError(SC_UNAUTHORIZED);
return false;
}
}
use of com.google.gerrit.server.auth.AuthenticationUnavailableException in project gerrit by GerritCodeReview.
the class LdapRealm method authenticate.
@Override
public AuthRequest authenticate(final AuthRequest who) throws AccountException {
if (config.getBoolean("ldap", "localUsernameToLowerCase", false)) {
who.setLocalUser(who.getLocalUser().toLowerCase(Locale.US));
}
final String username = who.getLocalUser();
try {
final DirContext ctx;
if (authConfig.getAuthType() == AuthType.LDAP_BIND) {
ctx = helper.authenticate(username, who.getPassword());
} else {
ctx = helper.open();
}
try {
final Helper.LdapSchema schema = helper.getSchema(ctx);
final LdapQuery.Result m = helper.findAccount(schema, ctx, username, fetchMemberOfEagerly);
if (authConfig.getAuthType() == AuthType.LDAP && !who.isSkipAuthentication()) {
// We found the user account, but we need to verify
// the password matches it before we can continue.
//
helper.authenticate(m.getDN(), who.getPassword()).close();
}
who.setDisplayName(apply(schema.accountFullName, m));
who.setUserName(apply(schema.accountSshUserName, m));
if (schema.accountEmailAddress != null) {
who.setEmailAddress(apply(schema.accountEmailAddress, m));
} else if (emailExpander.canExpand(username)) {
// If LDAP cannot give us a valid email address for this user
// try expanding it through the older email expander code which
// assumes a user name within a domain.
//
who.setEmailAddress(emailExpander.expand(username));
}
//
if (fetchMemberOfEagerly || mandatoryGroup != null) {
Set<AccountGroup.UUID> groups = helper.queryForGroups(ctx, username, m);
if (mandatoryGroup != null) {
GroupReference mandatoryGroupRef = GroupBackends.findExactSuggestion(groupBackend, mandatoryGroup);
if (mandatoryGroupRef == null) {
throw new AccountException("Could not identify mandatory group: " + mandatoryGroup);
}
if (!groups.contains(mandatoryGroupRef.getUUID())) {
throw new AccountException("Not member of mandatory LDAP group: " + mandatoryGroupRef.getName());
}
}
// Regardless if we enabled fetchMemberOfEagerly, we already have the
// groups and it would be a waste not to cache them.
membershipCache.put(username, groups);
}
return who;
} finally {
try {
ctx.close();
} catch (NamingException e) {
log.warn("Cannot close LDAP query handle", e);
}
}
} catch (NamingException e) {
log.error("Cannot query LDAP to authenticate user", e);
throw new AuthenticationUnavailableException("Cannot query LDAP for account", e);
} catch (LoginException e) {
log.error("Cannot authenticate server via JAAS", e);
throw new AuthenticationUnavailableException("Cannot query LDAP for account", e);
}
}
Aggregations