Search in sources :

Example 16 with AuthenticationException

use of com.hortonworks.registries.auth.client.AuthenticationException in project registry by hortonworks.

the class TestKerberosAuthenticationHandler method testRequestWithIncompleteAuthorization.

@Test(timeout = 60000)
public void testRequestWithIncompleteAuthorization() throws Exception {
    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
    Mockito.when(request.getHeader(KerberosAuthenticator.AUTHORIZATION)).thenReturn(KerberosAuthenticator.NEGOTIATE);
    try {
        handler.authenticate(request, response);
        Assert.fail();
    } catch (AuthenticationException ex) {
    // Expected
    } catch (Exception ex) {
        Assert.fail();
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthenticationException(com.hortonworks.registries.auth.client.AuthenticationException) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletException(javax.servlet.ServletException) AuthenticationException(com.hortonworks.registries.auth.client.AuthenticationException) Test(org.junit.Test)

Example 17 with AuthenticationException

use of com.hortonworks.registries.auth.client.AuthenticationException in project registry by hortonworks.

the class KerberosAuthenticationHandler method init.

/**
 * Initializes the authentication handler instance.
 * <p>
 * It creates a Kerberos context using the principal and keytab specified in the configuration.
 * <p>
 * This method is invoked by the {@link AuthenticationFilter#init} method.
 *
 * @param config configuration properties to initialize the handler.
 *
 * @throws ServletException thrown if the handler could not be initialized.
 */
@Override
public void init(Properties config) throws ServletException {
    try {
        String principal = config.getProperty(PRINCIPAL);
        if (principal == null || principal.trim().length() == 0) {
            throw new ServletException("Principal not defined in configuration");
        }
        keytab = config.getProperty(KEYTAB, keytab);
        if (keytab == null || keytab.trim().length() == 0) {
            throw new ServletException("Keytab not defined in configuration");
        }
        if (!new File(keytab).exists()) {
            throw new ServletException("Keytab does not exist: " + keytab);
        }
        // use all SPNEGO principals in the keytab if a principal isn't
        // specifically configured
        final String[] spnegoPrincipals;
        if (principal.equals("*")) {
            spnegoPrincipals = KerberosUtil.getPrincipalNames(keytab, Pattern.compile("HTTP/.*"));
            if (spnegoPrincipals.length == 0) {
                throw new ServletException("Principals do not exist in the keytab");
            }
        } else {
            spnegoPrincipals = new String[] { principal };
        }
        String nameRules = config.getProperty(NAME_RULES, null);
        if (nameRules != null) {
            KerberosName.setRules(nameRules);
        }
        for (String spnegoPrincipal : spnegoPrincipals) {
            LOG.info("Login using keytab {}, for principal {}", keytab, spnegoPrincipal);
            final KerberosConfiguration kerberosConfiguration = new KerberosConfiguration(keytab, spnegoPrincipal);
            final LoginContext loginContext = new LoginContext("", serverSubject, null, kerberosConfiguration);
            try {
                loginContext.login();
            } catch (LoginException le) {
                LOG.warn("Failed to login as [{}]", spnegoPrincipal, le);
                throw new AuthenticationException(le);
            }
            loginContexts.add(loginContext);
        }
        try {
            gssManager = Subject.doAs(serverSubject, new PrivilegedExceptionAction<GSSManager>() {

                @Override
                public GSSManager run() throws Exception {
                    return GSSManager.getInstance();
                }
            });
        } catch (PrivilegedActionException ex) {
            throw ex.getException();
        }
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
}
Also used : ServletException(javax.servlet.ServletException) LoginContext(javax.security.auth.login.LoginContext) AuthenticationException(com.hortonworks.registries.auth.client.AuthenticationException) PrivilegedActionException(java.security.PrivilegedActionException) LoginException(javax.security.auth.login.LoginException) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) File(java.io.File) LoginException(javax.security.auth.login.LoginException) ServletException(javax.servlet.ServletException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) AuthenticationException(com.hortonworks.registries.auth.client.AuthenticationException)

Example 18 with AuthenticationException

use of com.hortonworks.registries.auth.client.AuthenticationException in project registry by hortonworks.

the class AuthenticationFilter method getToken.

/**
 * Returns the {@link AuthenticationToken} for the request.
 * <p>
 * It looks at the received HTTP cookies and extracts the value of the {@link AuthenticatedURL#AUTH_COOKIE}
 * if present. It verifies the signature and if correct it creates the {@link AuthenticationToken} and returns
 * it.
 * <p>
 * If this method returns <code>null</code> the filter will invoke the configured {@link AuthenticationHandler}
 * to perform user authentication.
 *
 * @param request request object.
 *
 * @return the Authentication token if the request is authenticated, <code>null</code> otherwise.
 *
 * @throws IOException thrown if an IO error occurred.
 * @throws AuthenticationException thrown if the token is invalid or if it has expired.
 */
protected AuthenticationToken getToken(HttpServletRequest request) throws IOException, AuthenticationException {
    AuthenticationToken token = null;
    String tokenStr = null;
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(AuthenticatedURL.AUTH_COOKIE)) {
                tokenStr = cookie.getValue();
                try {
                    tokenStr = signer.verifyAndExtract(tokenStr);
                } catch (SignerException ex) {
                    throw new AuthenticationException(ex);
                }
                break;
            }
        }
    }
    if (tokenStr != null) {
        token = AuthenticationToken.parse(tokenStr);
        if (!token.getType().equals(authHandler.getType())) {
            throw new AuthenticationException("Invalid AuthenticationToken type");
        }
        if (token.isExpired()) {
            throw new AuthenticationException("AuthenticationToken expired");
        }
    }
    return token;
}
Also used : Cookie(javax.servlet.http.Cookie) AuthenticationException(com.hortonworks.registries.auth.client.AuthenticationException)

Example 19 with AuthenticationException

use of com.hortonworks.registries.auth.client.AuthenticationException in project registry by hortonworks.

the class AuthenticationFilter method doFilter.

/**
 * 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 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.
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, 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());
    if (isResourceAllowed(httpRequest)) {
        LOG.debug("Skipping kerberos authentication filter for {}", httpRequest);
        doFilter(filterChain, httpRequest, httpResponse);
    } else {
        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);
                    }
                    doFilter(filterChain, httpRequest, httpResponse);
                }
            } else {
                unauthorizedResponse = false;
            }
        } catch (AuthenticationException ex) {
            // exception from the filter itself is fatal
            errCode = HttpServletResponse.SC_FORBIDDEN;
            authenticationEx = ex;
            if (LOG.isDebugEnabled()) {
                LOG.debug("Authentication exception: " + ex.getMessage(), ex);
            } else {
                LOG.warn("Authentication exception: " + ex.getMessage());
            }
        }
        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) {
                    httpResponse.sendError(errCode, "Authentication required");
                } else {
                    httpResponse.sendError(errCode, authenticationEx.getMessage());
                }
            }
        }
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthenticationException(com.hortonworks.registries.auth.client.AuthenticationException) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) Principal(java.security.Principal)

Aggregations

AuthenticationException (com.hortonworks.registries.auth.client.AuthenticationException)19 HttpServletRequest (javax.servlet.http.HttpServletRequest)15 ServletException (javax.servlet.ServletException)13 Cookie (javax.servlet.http.Cookie)13 HttpServletResponse (javax.servlet.http.HttpServletResponse)13 Test (org.junit.Test)13 Properties (java.util.Properties)12 SignedJWT (com.nimbusds.jwt.SignedJWT)10 Date (java.util.Date)9 Signer (com.hortonworks.registries.auth.util.Signer)2 SignerSecretProvider (com.hortonworks.registries.auth.util.SignerSecretProvider)2 IOException (java.io.IOException)2 HttpCookie (java.net.HttpCookie)2 KeyPair (java.security.KeyPair)2 KeyPairGenerator (java.security.KeyPairGenerator)2 PrivilegedActionException (java.security.PrivilegedActionException)2 PrivilegedExceptionAction (java.security.PrivilegedExceptionAction)2 RSAPublicKey (java.security.interfaces.RSAPublicKey)2 Vector (java.util.Vector)2 FilterConfig (javax.servlet.FilterConfig)2