Search in sources :

Example 6 with AuthRequest

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

the class HttpLoginServlet method doGet.

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse rsp) throws ServletException, IOException {
    final String token = LoginUrlToken.getToken(req);
    CacheHeaders.setNotCacheable(rsp);
    final String user = authFilter.getRemoteUser(req);
    if (user == null || "".equals(user)) {
        log.error("Unable to authenticate user by " + authFilter.getLoginHeader() + " request header.  Check container or server configuration.");
        final Document doc = //
        HtmlDomUtil.parseFile(HttpLoginServlet.class, "ConfigurationError.html");
        replace(doc, "loginHeader", authFilter.getLoginHeader());
        replace(doc, "ServerName", req.getServerName());
        replace(doc, "ServerPort", ":" + req.getServerPort());
        replace(doc, "ContextPath", req.getContextPath());
        final byte[] bin = HtmlDomUtil.toUTF8(doc);
        rsp.setStatus(HttpServletResponse.SC_FORBIDDEN);
        rsp.setContentType("text/html");
        rsp.setCharacterEncoding(UTF_8.name());
        rsp.setContentLength(bin.length);
        try (ServletOutputStream out = rsp.getOutputStream()) {
            out.write(bin);
        }
        return;
    }
    final AuthRequest areq = AuthRequest.forUser(user);
    areq.setDisplayName(authFilter.getRemoteDisplayname(req));
    areq.setEmailAddress(authFilter.getRemoteEmail(req));
    final AuthResult arsp;
    try {
        arsp = accountManager.authenticate(areq);
    } catch (AccountException e) {
        log.error("Unable to authenticate user \"" + user + "\"", e);
        rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    String remoteExternalId = authFilter.getRemoteExternalIdToken(req);
    if (remoteExternalId != null) {
        try {
            log.debug("Associating external identity \"{}\" to user \"{}\"", remoteExternalId, user);
            updateRemoteExternalId(arsp, remoteExternalId);
        } catch (AccountException | OrmException | ConfigInvalidException e) {
            log.error("Unable to associate external identity \"" + remoteExternalId + "\" to user \"" + user + "\"", e);
            rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }
    }
    final StringBuilder rdr = new StringBuilder();
    if (arsp.isNew() && authConfig.getRegisterPageUrl() != null) {
        rdr.append(authConfig.getRegisterPageUrl());
    } else {
        rdr.append(urlProvider.get(req));
        if (arsp.isNew() && !token.startsWith(PageLinks.REGISTER + "/")) {
            rdr.append('#' + PageLinks.REGISTER);
        }
        rdr.append(token);
    }
    webSession.get().login(arsp, true);
    rsp.sendRedirect(rdr.toString());
}
Also used : AuthRequest(com.google.gerrit.server.account.AuthRequest) AccountException(com.google.gerrit.server.account.AccountException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) ServletOutputStream(javax.servlet.ServletOutputStream) OrmException(com.google.gwtorm.server.OrmException) AuthResult(com.google.gerrit.server.account.AuthResult) Document(org.w3c.dom.Document)

Example 7 with AuthRequest

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

the class ProjectOAuthFilter method verify.

private boolean verify(HttpServletRequest req, Response rsp) throws IOException {
    AuthInfo authInfo = null;
    // first check if there is a BASIC authentication header
    String hdr = req.getHeader(AUTHORIZATION);
    if (hdr != null && hdr.startsWith(BASIC)) {
        authInfo = extractAuthInfo(hdr, encoding(req));
        if (authInfo == null) {
            rsp.sendError(SC_UNAUTHORIZED);
            return false;
        }
    } else {
        // if there is no BASIC authentication header, check if there is
        // a cookie starting with the prefix "git-"
        Cookie cookie = findGitCookie(req);
        if (cookie != null) {
            authInfo = extractAuthInfo(cookie);
            if (authInfo == null) {
                rsp.sendError(SC_UNAUTHORIZED);
                return false;
            }
        } else {
            // an anonymous connection, or there might be a session cookie
            return true;
        }
    }
    // if there is authentication information but no secret => 401
    if (Strings.isNullOrEmpty(authInfo.tokenOrSecret)) {
        rsp.sendError(SC_UNAUTHORIZED);
        return false;
    }
    AccountState who = accountCache.getByUsername(authInfo.username);
    if (who == null || !who.getAccount().isActive()) {
        log.warn("Authentication failed for " + authInfo.username + ": account inactive or not provisioned in Gerrit");
        rsp.sendError(SC_UNAUTHORIZED);
        return false;
    }
    AuthRequest authRequest = AuthRequest.forExternalUser(authInfo.username);
    authRequest.setEmailAddress(who.getAccount().getPreferredEmail());
    authRequest.setDisplayName(who.getAccount().getFullName());
    authRequest.setPassword(authInfo.tokenOrSecret);
    authRequest.setAuthPlugin(authInfo.pluginName);
    authRequest.setAuthProvider(authInfo.exportName);
    try {
        AuthResult authResult = accountManager.authenticate(authRequest);
        WebSession ws = session.get();
        ws.setUserAccountId(authResult.getAccountId());
        ws.setAccessPathOk(AccessPath.GIT, true);
        ws.setAccessPathOk(AccessPath.REST_API, true);
        return true;
    } catch (AccountException e) {
        log.warn("Authentication failed for " + authInfo.username, e);
        rsp.sendError(SC_UNAUTHORIZED);
        return false;
    }
}
Also used : Cookie(javax.servlet.http.Cookie) AuthRequest(com.google.gerrit.server.account.AuthRequest) AccountException(com.google.gerrit.server.account.AccountException) AuthResult(com.google.gerrit.server.account.AuthResult) AccountState(com.google.gerrit.server.account.AccountState)

Example 8 with AuthRequest

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

the class OAuthSession method authenticateAndRedirect.

private void authenticateAndRedirect(HttpServletRequest req, HttpServletResponse rsp, OAuthToken token) throws IOException {
    AuthRequest areq = new AuthRequest(ExternalId.Key.parse(user.getExternalId()));
    AuthResult arsp;
    try {
        String claimedIdentifier = user.getClaimedIdentity();
        if (!Strings.isNullOrEmpty(claimedIdentifier)) {
            if (!authenticateWithIdentityClaimedDuringHandshake(areq, rsp, claimedIdentifier)) {
                return;
            }
        } else if (linkMode) {
            if (!authenticateWithLinkedIdentity(areq, rsp)) {
                return;
            }
        }
        areq.setUserName(user.getUserName());
        areq.setEmailAddress(user.getEmailAddress());
        areq.setDisplayName(user.getDisplayName());
        arsp = accountManager.authenticate(areq);
        accountId = arsp.getAccountId();
        tokenCache.put(accountId, token);
    } catch (AccountException e) {
        log.error("Unable to authenticate user \"" + user + "\"", e);
        rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    webSession.get().login(arsp, true);
    String suffix = redirectToken.substring(OAuthWebFilter.GERRIT_LOGIN.length() + 1);
    suffix = CharMatcher.anyOf("/").trimLeadingFrom(Url.decode(suffix));
    StringBuilder rdr = new StringBuilder(urlProvider.get(req));
    rdr.append(suffix);
    rsp.sendRedirect(rdr.toString());
}
Also used : AuthRequest(com.google.gerrit.server.account.AuthRequest) AccountException(com.google.gerrit.server.account.AccountException) AuthResult(com.google.gerrit.server.account.AuthResult)

Example 9 with AuthRequest

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

the class AccountIdHandler method createAccountByLdap.

private Account.Id createAccountByLdap(String user) throws CmdLineException, IOException {
    if (!user.matches(Account.USER_NAME_PATTERN)) {
        throw new CmdLineException(owner, "user \"" + user + "\" not found");
    }
    try {
        AuthRequest req = AuthRequest.forUser(user);
        req.setSkipAuthentication(true);
        return accountManager.authenticate(req).getAccountId();
    } catch (AccountException e) {
        throw new CmdLineException(owner, "user \"" + user + "\" not found");
    }
}
Also used : AuthRequest(com.google.gerrit.server.account.AuthRequest) AccountException(com.google.gerrit.server.account.AccountException) CmdLineException(org.kohsuke.args4j.CmdLineException)

Aggregations

AuthRequest (com.google.gerrit.server.account.AuthRequest)9 AccountException (com.google.gerrit.server.account.AccountException)8 AuthResult (com.google.gerrit.server.account.AuthResult)6 AccountState (com.google.gerrit.server.account.AccountState)2 GitBasicAuthPolicy (com.google.gerrit.extensions.client.GitBasicAuthPolicy)1 Account (com.google.gerrit.reviewdb.client.Account)1 AccountUserNameException (com.google.gerrit.server.account.AccountUserNameException)1 AuthenticationFailedException (com.google.gerrit.server.account.AuthenticationFailedException)1 AuthenticationUnavailableException (com.google.gerrit.server.auth.AuthenticationUnavailableException)1 NoSuchUserException (com.google.gerrit.server.auth.NoSuchUserException)1 OrmException (com.google.gwtorm.server.OrmException)1 X509Certificate (java.security.cert.X509Certificate)1 Matcher (java.util.regex.Matcher)1 ServletException (javax.servlet.ServletException)1 ServletOutputStream (javax.servlet.ServletOutputStream)1 Cookie (javax.servlet.http.Cookie)1 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)1 CmdLineException (org.kohsuke.args4j.CmdLineException)1 Document (org.w3c.dom.Document)1