Search in sources :

Example 1 with AuthenticationToken

use of org.apache.hadoop.security.authentication.server.AuthenticationToken in project hadoop by apache.

the class DelegationTokenAuthenticationHandler method authenticate.

/**
   * Authenticates a request looking for the <code>delegation</code>
   * query-string parameter and verifying it is a valid token. If there is not
   * <code>delegation</code> query-string parameter, it delegates the
   * authentication to the {@link KerberosAuthenticationHandler} unless it is
   * disabled.
   *
   * @param request the HTTP client request.
   * @param response the HTTP client response.
   * @return the authentication token for the authenticated request.
   * @throws IOException thrown if an IO error occurred.
   * @throws AuthenticationException thrown if the authentication failed.
   */
@SuppressWarnings("unchecked")
@Override
public AuthenticationToken authenticate(HttpServletRequest request, HttpServletResponse response) throws IOException, AuthenticationException {
    AuthenticationToken token;
    String delegationParam = getDelegationToken(request);
    if (delegationParam != null) {
        try {
            Token<AbstractDelegationTokenIdentifier> dt = new Token();
            dt.decodeFromUrlString(delegationParam);
            UserGroupInformation ugi = tokenManager.verifyToken(dt);
            final String shortName = ugi.getShortUserName();
            // creating a ephemeral token
            token = new AuthenticationToken(shortName, ugi.getUserName(), getType());
            token.setExpires(0);
            request.setAttribute(DELEGATION_TOKEN_UGI_ATTRIBUTE, ugi);
        } catch (Throwable ex) {
            token = null;
            HttpExceptionUtils.createServletExceptionResponse(response, HttpServletResponse.SC_FORBIDDEN, new AuthenticationException(ex));
        }
    } else {
        token = authHandler.authenticate(request, response);
    }
    return token;
}
Also used : AbstractDelegationTokenIdentifier(org.apache.hadoop.security.token.delegation.AbstractDelegationTokenIdentifier) AuthenticationToken(org.apache.hadoop.security.authentication.server.AuthenticationToken) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) AuthenticationToken(org.apache.hadoop.security.authentication.server.AuthenticationToken) Token(org.apache.hadoop.security.token.Token) UserGroupInformation(org.apache.hadoop.security.UserGroupInformation)

Example 2 with AuthenticationToken

use of org.apache.hadoop.security.authentication.server.AuthenticationToken in project hadoop by apache.

the class DelegationTokenAuthenticationHandler method managementOperation.

@Override
@SuppressWarnings("unchecked")
public boolean managementOperation(AuthenticationToken token, HttpServletRequest request, HttpServletResponse response) throws IOException, AuthenticationException {
    boolean requestContinues = true;
    String op = ServletUtils.getParameter(request, KerberosDelegationTokenAuthenticator.OP_PARAM);
    op = (op != null) ? StringUtils.toUpperCase(op) : null;
    if (isManagementOperation(request)) {
        KerberosDelegationTokenAuthenticator.DelegationTokenOperation dtOp = KerberosDelegationTokenAuthenticator.DelegationTokenOperation.valueOf(op);
        if (dtOp.getHttpMethod().equals(request.getMethod())) {
            boolean doManagement;
            if (dtOp.requiresKerberosCredentials() && token == null) {
                // Don't authenticate via DT for DT ops.
                token = authHandler.authenticate(request, response);
                if (token == null) {
                    requestContinues = false;
                    doManagement = false;
                } else {
                    doManagement = true;
                }
            } else {
                doManagement = true;
            }
            if (doManagement) {
                UserGroupInformation requestUgi = (token != null) ? UserGroupInformation.createRemoteUser(token.getUserName()) : null;
                // Create the proxy user if doAsUser exists
                String doAsUser = DelegationTokenAuthenticationFilter.getDoAs(request);
                if (requestUgi != null && doAsUser != null) {
                    requestUgi = UserGroupInformation.createProxyUser(doAsUser, requestUgi);
                    try {
                        ProxyUsers.authorize(requestUgi, request.getRemoteAddr());
                    } catch (AuthorizationException ex) {
                        HttpExceptionUtils.createServletExceptionResponse(response, HttpServletResponse.SC_FORBIDDEN, ex);
                        return false;
                    }
                }
                Map map = null;
                switch(dtOp) {
                    case GETDELEGATIONTOKEN:
                        if (requestUgi == null) {
                            throw new IllegalStateException("request UGI cannot be NULL");
                        }
                        String renewer = ServletUtils.getParameter(request, KerberosDelegationTokenAuthenticator.RENEWER_PARAM);
                        try {
                            Token<?> dToken = tokenManager.createToken(requestUgi, renewer);
                            map = delegationTokenToJSON(dToken);
                        } catch (IOException ex) {
                            throw new AuthenticationException(ex.toString(), ex);
                        }
                        break;
                    case RENEWDELEGATIONTOKEN:
                        if (requestUgi == null) {
                            throw new IllegalStateException("request UGI cannot be NULL");
                        }
                        String tokenToRenew = ServletUtils.getParameter(request, KerberosDelegationTokenAuthenticator.TOKEN_PARAM);
                        if (tokenToRenew == null) {
                            response.sendError(HttpServletResponse.SC_BAD_REQUEST, MessageFormat.format("Operation [{0}] requires the parameter [{1}]", dtOp, KerberosDelegationTokenAuthenticator.TOKEN_PARAM));
                            requestContinues = false;
                        } else {
                            Token<AbstractDelegationTokenIdentifier> dt = new Token();
                            try {
                                dt.decodeFromUrlString(tokenToRenew);
                                long expirationTime = tokenManager.renewToken(dt, requestUgi.getShortUserName());
                                map = new HashMap();
                                map.put("long", expirationTime);
                            } catch (IOException ex) {
                                throw new AuthenticationException(ex.toString(), ex);
                            }
                        }
                        break;
                    case CANCELDELEGATIONTOKEN:
                        String tokenToCancel = ServletUtils.getParameter(request, KerberosDelegationTokenAuthenticator.TOKEN_PARAM);
                        if (tokenToCancel == null) {
                            response.sendError(HttpServletResponse.SC_BAD_REQUEST, MessageFormat.format("Operation [{0}] requires the parameter [{1}]", dtOp, KerberosDelegationTokenAuthenticator.TOKEN_PARAM));
                            requestContinues = false;
                        } else {
                            Token<AbstractDelegationTokenIdentifier> dt = new Token();
                            try {
                                dt.decodeFromUrlString(tokenToCancel);
                                tokenManager.cancelToken(dt, (requestUgi != null) ? requestUgi.getShortUserName() : null);
                            } catch (IOException ex) {
                                response.sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid delegation token, cannot cancel");
                                requestContinues = false;
                            }
                        }
                        break;
                }
                if (requestContinues) {
                    response.setStatus(HttpServletResponse.SC_OK);
                    if (map != null) {
                        response.setContentType(MediaType.APPLICATION_JSON);
                        Writer writer = response.getWriter();
                        ObjectMapper jsonMapper = new ObjectMapper(jsonFactory);
                        jsonMapper.writeValue(writer, map);
                        writer.write(ENTER);
                        writer.flush();
                    }
                    requestContinues = false;
                }
            }
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, MessageFormat.format("Wrong HTTP method [{0}] for operation [{1}], it should be " + "[{2}]", request.getMethod(), dtOp, dtOp.getHttpMethod()));
            requestContinues = false;
        }
    }
    return requestContinues;
}
Also used : AuthorizationException(org.apache.hadoop.security.authorize.AuthorizationException) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) AuthenticationToken(org.apache.hadoop.security.authentication.server.AuthenticationToken) Token(org.apache.hadoop.security.token.Token) IOException(java.io.IOException) AbstractDelegationTokenIdentifier(org.apache.hadoop.security.token.delegation.AbstractDelegationTokenIdentifier) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) Writer(java.io.Writer) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) UserGroupInformation(org.apache.hadoop.security.UserGroupInformation)

Example 3 with AuthenticationToken

use of org.apache.hadoop.security.authentication.server.AuthenticationToken in project hadoop by apache.

the class TestDelegationTokenAuthenticationHandlerWithMocks method testRenewToken.

@SuppressWarnings("unchecked")
private void testRenewToken() throws Exception {
    DelegationTokenAuthenticator.DelegationTokenOperation op = DelegationTokenAuthenticator.DelegationTokenOperation.RENEWDELEGATIONTOKEN;
    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
    Mockito.when(request.getQueryString()).thenReturn(DelegationTokenAuthenticator.OP_PARAM + "=" + op.toString());
    Mockito.when(request.getMethod()).thenReturn(op.getHttpMethod());
    Assert.assertFalse(handler.managementOperation(null, request, response));
    Mockito.verify(response).setStatus(Mockito.eq(HttpServletResponse.SC_UNAUTHORIZED));
    Mockito.verify(response).setHeader(Mockito.eq(KerberosAuthenticator.WWW_AUTHENTICATE), Mockito.eq("mock"));
    Mockito.reset(response);
    AuthenticationToken token = Mockito.mock(AuthenticationToken.class);
    Mockito.when(token.getUserName()).thenReturn("user");
    Assert.assertFalse(handler.managementOperation(token, request, response));
    Mockito.verify(response).sendError(Mockito.eq(HttpServletResponse.SC_BAD_REQUEST), Mockito.contains("requires the parameter [token]"));
    Mockito.reset(response);
    StringWriter writer = new StringWriter();
    PrintWriter pwriter = new PrintWriter(writer);
    Mockito.when(response.getWriter()).thenReturn(pwriter);
    Token<DelegationTokenIdentifier> dToken = (Token<DelegationTokenIdentifier>) handler.getTokenManager().createToken(UserGroupInformation.getCurrentUser(), "user");
    Mockito.when(request.getQueryString()).thenReturn(DelegationTokenAuthenticator.OP_PARAM + "=" + op.toString() + "&" + DelegationTokenAuthenticator.TOKEN_PARAM + "=" + dToken.encodeToUrlString());
    Assert.assertFalse(handler.managementOperation(token, request, response));
    Mockito.verify(response).setStatus(HttpServletResponse.SC_OK);
    pwriter.close();
    Assert.assertTrue(writer.toString().contains("long"));
    handler.getTokenManager().verifyToken(dToken);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthenticationToken(org.apache.hadoop.security.authentication.server.AuthenticationToken) StringWriter(java.io.StringWriter) HttpServletResponse(javax.servlet.http.HttpServletResponse) DelegationTokenOperation(org.apache.hadoop.security.token.delegation.web.DelegationTokenAuthenticator.DelegationTokenOperation) AuthenticationToken(org.apache.hadoop.security.authentication.server.AuthenticationToken) Token(org.apache.hadoop.security.token.Token) PrintWriter(java.io.PrintWriter)

Example 4 with AuthenticationToken

use of org.apache.hadoop.security.authentication.server.AuthenticationToken in project hadoop by apache.

the class TestDelegationTokenAuthenticationHandlerWithMocks method testValidDelegationTokenHeader.

@SuppressWarnings("unchecked")
private void testValidDelegationTokenHeader() throws Exception {
    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
    Token<DelegationTokenIdentifier> dToken = (Token<DelegationTokenIdentifier>) handler.getTokenManager().createToken(UserGroupInformation.getCurrentUser(), "user");
    Mockito.when(request.getHeader(Mockito.eq(DelegationTokenAuthenticator.DELEGATION_TOKEN_HEADER))).thenReturn(dToken.encodeToUrlString());
    AuthenticationToken token = handler.authenticate(request, response);
    Assert.assertEquals(UserGroupInformation.getCurrentUser().getShortUserName(), token.getUserName());
    Assert.assertEquals(0, token.getExpires());
    Assert.assertEquals(handler.getType(), token.getType());
    Assert.assertTrue(token.isExpired());
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthenticationToken(org.apache.hadoop.security.authentication.server.AuthenticationToken) HttpServletResponse(javax.servlet.http.HttpServletResponse) AuthenticationToken(org.apache.hadoop.security.authentication.server.AuthenticationToken) Token(org.apache.hadoop.security.token.Token)

Example 5 with AuthenticationToken

use of org.apache.hadoop.security.authentication.server.AuthenticationToken in project incubator-atlas by apache.

the class AtlasAuthenticationFilter method doKerberosAuth.

/**
     * This method is copied from hadoop auth lib, code added for error handling and fallback to other auth methods
     *
     * If the request has a valid authentication token it allows the request to continue to the target resource,
     * otherwise it triggers an authentication sequence using the configured {@link org.apache.hadoop.security.authentication.server.AuthenticationHandler}.
     *
     * @param request     the request object.
     * @param response    the response object.
     * @param filterChain the filter chain object.
     *
     * @throws IOException      thrown if an IO error occurred.
     * @throws ServletException thrown if a processing error occurred.
     */
public void doKerberosAuth(ServletRequest request, ServletResponse response, FilterChain filterChainWrapper, FilterChain filterChain) throws IOException, ServletException {
    boolean unauthorizedResponse = true;
    int errCode = HttpServletResponse.SC_UNAUTHORIZED;
    AuthenticationException authenticationEx = null;
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    boolean isHttps = "https".equals(httpRequest.getScheme());
    AuthenticationHandler authHandler = getAuthenticationHandler();
    try {
        boolean newToken = false;
        AuthenticationToken token;
        try {
            token = getToken(httpRequest);
        } catch (AuthenticationException ex) {
            LOG.warn("AuthenticationToken ignored: {}", ex.getMessage());
            // will be sent back in a 401 unless filter authenticates
            authenticationEx = ex;
            token = null;
        }
        if (authHandler.managementOperation(token, httpRequest, httpResponse)) {
            if (token == null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Request [{}] triggering authentication", getRequestURL(httpRequest));
                }
                token = authHandler.authenticate(httpRequest, httpResponse);
                if (token != null && token.getExpires() != 0 && token != AuthenticationToken.ANONYMOUS) {
                    token.setExpires(System.currentTimeMillis() + getValidity() * 1000);
                }
                newToken = true;
            }
            if (token != null) {
                unauthorizedResponse = false;
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Request [{}] user [{}] authenticated", getRequestURL(httpRequest), token.getUserName());
                }
                final AuthenticationToken authToken = token;
                httpRequest = new HttpServletRequestWrapper(httpRequest) {

                    @Override
                    public String getAuthType() {
                        return authToken.getType();
                    }

                    @Override
                    public String getRemoteUser() {
                        return authToken.getUserName();
                    }

                    @Override
                    public Principal getUserPrincipal() {
                        return (authToken != AuthenticationToken.ANONYMOUS) ? authToken : null;
                    }
                };
                if (newToken && !token.isExpired() && token != AuthenticationToken.ANONYMOUS) {
                    String signedToken = signer.sign(token.toString());
                    createAuthCookie(httpResponse, signedToken, getCookieDomain(), getCookiePath(), token.getExpires(), isHttps);
                }
                filterChainWrapper.doFilter(httpRequest, httpResponse);
            }
        } else {
            unauthorizedResponse = false;
        }
    } catch (AuthenticationException ex) {
        // exception from the filter itself is fatal
        errCode = HttpServletResponse.SC_FORBIDDEN;
        authenticationEx = ex;
        LOG.warn("Authentication exception: {}", ex.getMessage(), ex);
    }
    if (unauthorizedResponse) {
        if (!httpResponse.isCommitted()) {
            createAuthCookie(httpResponse, "", getCookieDomain(), getCookiePath(), 0, isHttps);
            // present.. reset to 403 if not found..
            if ((errCode == HttpServletResponse.SC_UNAUTHORIZED) && (!httpResponse.containsHeader(KerberosAuthenticator.WWW_AUTHENTICATE))) {
                errCode = HttpServletResponse.SC_FORBIDDEN;
            }
            if (authenticationEx == null) {
                // added this code for atlas error handling and fallback
                if (!supportKeyTabBrowserLogin && isBrowser(httpRequest.getHeader("User-Agent"))) {
                    filterChain.doFilter(request, response);
                } else {
                    boolean chk = true;
                    Collection<String> headerNames = httpResponse.getHeaderNames();
                    for (String headerName : headerNames) {
                        String value = httpResponse.getHeader(headerName);
                        if (headerName.equalsIgnoreCase("Set-Cookie") && value.startsWith("ATLASSESSIONID")) {
                            chk = false;
                            break;
                        }
                    }
                    String authHeader = httpRequest.getHeader("Authorization");
                    if (authHeader == null && chk) {
                        filterChain.doFilter(request, response);
                    } else if (authHeader != null && authHeader.startsWith("Basic")) {
                        filterChain.doFilter(request, response);
                    }
                }
            } else {
                httpResponse.sendError(errCode, authenticationEx.getMessage());
            }
        }
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) AuthenticationToken(org.apache.hadoop.security.authentication.server.AuthenticationToken) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) KerberosAuthenticationHandler(org.apache.hadoop.security.authentication.server.KerberosAuthenticationHandler) AuthenticationHandler(org.apache.hadoop.security.authentication.server.AuthenticationHandler) Principal(java.security.Principal)

Aggregations

AuthenticationToken (org.apache.hadoop.security.authentication.server.AuthenticationToken)13 HttpServletRequest (javax.servlet.http.HttpServletRequest)7 HttpServletResponse (javax.servlet.http.HttpServletResponse)7 Token (org.apache.hadoop.security.token.Token)7 PrintWriter (java.io.PrintWriter)4 StringWriter (java.io.StringWriter)4 AuthenticationException (org.apache.hadoop.security.authentication.client.AuthenticationException)4 DelegationTokenOperation (org.apache.hadoop.security.token.delegation.web.DelegationTokenAuthenticator.DelegationTokenOperation)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 Map (java.util.Map)3 UserGroupInformation (org.apache.hadoop.security.UserGroupInformation)3 Principal (java.security.Principal)2 Properties (java.util.Properties)2 HttpServletRequestWrapper (javax.servlet.http.HttpServletRequestWrapper)2 AuthenticationHandler (org.apache.hadoop.security.authentication.server.AuthenticationHandler)2 KerberosAuthenticationHandler (org.apache.hadoop.security.authentication.server.KerberosAuthenticationHandler)2 AuthorizationException (org.apache.hadoop.security.authorize.AuthorizationException)2 AbstractDelegationTokenIdentifier (org.apache.hadoop.security.token.delegation.AbstractDelegationTokenIdentifier)2 Test (org.junit.Test)2 AbstractAuthenticationToken (org.springframework.security.authentication.AbstractAuthenticationToken)2