Search in sources :

Example 1 with AuthRequest

use of com.google.gerrit.server.account.AuthRequest in project gerrit by GerritCodeReview.

the class AddMembers method createAccountByLdap.

private Account createAccountByLdap(String user) throws IOException {
    if (!user.matches(Account.USER_NAME_PATTERN)) {
        return null;
    }
    try {
        AuthRequest req = AuthRequest.forUser(user);
        req.setSkipAuthentication(true);
        return accountCache.get(accountManager.authenticate(req).getAccountId()).getAccount();
    } catch (AccountException e) {
        return null;
    }
}
Also used : AuthRequest(com.google.gerrit.server.account.AuthRequest) AccountException(com.google.gerrit.server.account.AccountException)

Example 2 with AuthRequest

use of com.google.gerrit.server.account.AuthRequest in project gerrit by GerritCodeReview.

the class HttpsClientSslCertAuthFilter method doFilter.

@Override
public void doFilter(ServletRequest req, ServletResponse rsp, FilterChain chain) throws IOException, ServletException {
    X509Certificate[] certs = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
    if (certs == null || certs.length == 0) {
        throw new ServletException("Couldn't get the attribute javax.servlet.request.X509Certificate from the request");
    }
    String name = certs[0].getSubjectDN().getName();
    Matcher m = REGEX_USERID.matcher(name);
    String userName;
    if (m.find()) {
        userName = m.group(1);
    } else {
        throw new ServletException("Couldn't extract username from your certificate");
    }
    final AuthRequest areq = authRequestFactory.createForUser(userName);
    final AuthResult arsp;
    try {
        arsp = accountManager.authenticate(areq);
    } catch (AccountException e) {
        throw new ServletException("Unable to authenticate user \"" + userName + "\"", e);
    }
    webSession.get().login(arsp, true);
    chain.doFilter(req, rsp);
}
Also used : ServletException(javax.servlet.ServletException) AuthRequest(com.google.gerrit.server.account.AuthRequest) AccountException(com.google.gerrit.server.account.AccountException) Matcher(java.util.regex.Matcher) AuthResult(com.google.gerrit.server.account.AuthResult) X509Certificate(java.security.cert.X509Certificate)

Example 3 with AuthRequest

use of com.google.gerrit.server.account.AuthRequest 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());
}
Also used : AuthRequest(com.google.gerrit.server.account.AuthRequest) AccountUserNameException(com.google.gerrit.server.account.AccountUserNameException) AuthenticationUnavailableException(com.google.gerrit.server.auth.AuthenticationUnavailableException) AccountException(com.google.gerrit.server.account.AccountException) AuthenticationFailedException(com.google.gerrit.server.account.AuthenticationFailedException) AuthResult(com.google.gerrit.server.account.AuthResult)

Example 4 with AuthRequest

use of com.google.gerrit.server.account.AuthRequest 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;
    }
}
Also used : AuthRequest(com.google.gerrit.server.account.AuthRequest) AuthenticationUnavailableException(com.google.gerrit.server.auth.AuthenticationUnavailableException) AccountException(com.google.gerrit.server.account.AccountException) AuthenticationFailedException(com.google.gerrit.server.account.AuthenticationFailedException) NoSuchUserException(com.google.gerrit.server.auth.NoSuchUserException) GitBasicAuthPolicy(com.google.gerrit.extensions.client.GitBasicAuthPolicy) AuthResult(com.google.gerrit.server.account.AuthResult) AccountState(com.google.gerrit.server.account.AccountState)

Example 5 with AuthRequest

use of com.google.gerrit.server.account.AuthRequest in project gerrit by GerritCodeReview.

the class AddMembers method createAccountByLdap.

private Optional<Account> createAccountByLdap(String user) throws IOException {
    if (!ExternalId.isValidUsername(user)) {
        return Optional.empty();
    }
    try {
        AuthRequest req = authRequestFactory.createForUser(user);
        req.setSkipAuthentication(true);
        return accountCache.get(accountManager.authenticate(req).getAccountId()).map(AccountState::account);
    } catch (AccountException e) {
        return Optional.empty();
    }
}
Also used : AuthRequest(com.google.gerrit.server.account.AuthRequest) UnresolvableAccountException(com.google.gerrit.server.account.AccountResolver.UnresolvableAccountException) AccountException(com.google.gerrit.server.account.AccountException) AccountState(com.google.gerrit.server.account.AccountState)

Aggregations

AuthRequest (com.google.gerrit.server.account.AuthRequest)36 ExternalId (com.google.gerrit.server.account.externalids.ExternalId)25 Test (org.junit.Test)25 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)24 Account (com.google.gerrit.entities.Account)23 AuthResult (com.google.gerrit.server.account.AuthResult)22 AccountException (com.google.gerrit.server.account.AccountException)18 AccountState (com.google.gerrit.server.account.AccountState)10 GerritConfig (com.google.gerrit.acceptance.config.GerritConfig)2 AuthenticationFailedException (com.google.gerrit.server.account.AuthenticationFailedException)2 AuthenticationUnavailableException (com.google.gerrit.server.auth.AuthenticationUnavailableException)2 Change (com.google.gerrit.entities.Change)1 GitBasicAuthPolicy (com.google.gerrit.extensions.client.GitBasicAuthPolicy)1 UnresolvableAccountException (com.google.gerrit.server.account.AccountResolver.UnresolvableAccountException)1 AccountUserNameException (com.google.gerrit.server.account.AccountUserNameException)1 ExternalIdNotes (com.google.gerrit.server.account.externalids.ExternalIdNotes)1 NoSuchUserException (com.google.gerrit.server.auth.NoSuchUserException)1 MetaDataUpdate (com.google.gerrit.server.git.meta.MetaDataUpdate)1 ManualRequestContext (com.google.gerrit.server.util.ManualRequestContext)1 Repo (com.google.gerrit.testing.InMemoryRepositoryManager.Repo)1