Search in sources :

Example 6 with AuthenticationException

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

the class TestJWTAuthenticationHandler method testInvalidAudienceJWT.

@Test
public void testInvalidAudienceJWT() throws Exception {
    try {
        handler.setPublicKey(publicKey);
        Properties props = getProperties();
        props.put(JWTAuthenticationHandler.EXPECTED_JWT_AUDIENCES, "foo");
        handler.init(props);
        SignedJWT jwt = getJWT("bob", new Date(new Date().getTime() + 5000), privateKey);
        Cookie cookie = new Cookie("hadoop-jwt", jwt.serialize());
        HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
        Mockito.when(request.getCookies()).thenReturn(new Cookie[] { cookie });
        Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer(SERVICE_URL));
        HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
        Mockito.when(response.encodeRedirectURL(SERVICE_URL)).thenReturn(SERVICE_URL);
        AuthenticationToken token = handler.alternateAuthenticate(request, response);
        Mockito.verify(response).sendRedirect(REDIRECT_LOCATION);
    } catch (ServletException se) {
        fail("alternateAuthentication should NOT have thrown a ServletException");
    } catch (AuthenticationException ae) {
        fail("alternateAuthentication should NOT have thrown a AuthenticationException");
    }
}
Also used : Cookie(javax.servlet.http.Cookie) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) AuthenticationException(com.hortonworks.registries.auth.client.AuthenticationException) HttpServletResponse(javax.servlet.http.HttpServletResponse) SignedJWT(com.nimbusds.jwt.SignedJWT) Properties(java.util.Properties) Date(java.util.Date) Test(org.junit.Test)

Example 7 with AuthenticationException

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

the class KerberosAuthenticationHandler method authenticate.

/**
 * It enforces the the Kerberos SPNEGO authentication sequence returning an {@link AuthenticationToken} only
 * after the Kerberos SPNEGO sequence has completed successfully.
 *
 * @param request the HTTP client request.
 * @param response the HTTP client response.
 *
 * @return an authentication token if the Kerberos SPNEGO sequence is complete and valid,
 *         <code>null</code> if it is in progress (in this case the handler handles the response to the client).
 *
 * @throws IOException thrown if an IO error occurred.
 * @throws AuthenticationException thrown if Kerberos SPNEGO sequence failed.
 */
@Override
public AuthenticationToken authenticate(HttpServletRequest request, final HttpServletResponse response) throws IOException, AuthenticationException {
    AuthenticationToken token = null;
    String authorization = request.getHeader(KerberosAuthenticator.AUTHORIZATION);
    if (authorization == null || !authorization.startsWith(KerberosAuthenticator.NEGOTIATE)) {
        response.setHeader(WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE);
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        if (authorization == null) {
            LOG.trace("SPNEGO starting");
        } else {
            LOG.warn("'" + KerberosAuthenticator.AUTHORIZATION + "' does not start with '" + KerberosAuthenticator.NEGOTIATE + "' :  {}", authorization);
        }
    } else {
        authorization = authorization.substring(KerberosAuthenticator.NEGOTIATE.length()).trim();
        final byte[] clientToken = Base64.getDecoder().decode(authorization);
        final String serverName = request.getServerName();
        try {
            token = Subject.doAs(serverSubject, new PrivilegedExceptionAction<AuthenticationToken>() {

                @Override
                public AuthenticationToken run() throws Exception {
                    AuthenticationToken token = null;
                    GSSContext gssContext = null;
                    GSSCredential gssCreds = null;
                    try {
                        gssCreds = gssManager.createCredential(gssManager.createName(KerberosUtil.getServicePrincipal("HTTP", serverName), KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL")), GSSCredential.INDEFINITE_LIFETIME, new Oid[] { KerberosUtil.getOidInstance("GSS_SPNEGO_MECH_OID"), KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID") }, GSSCredential.ACCEPT_ONLY);
                        gssContext = gssManager.createContext(gssCreds);
                        byte[] serverToken = gssContext.acceptSecContext(clientToken, 0, clientToken.length);
                        if (serverToken != null && serverToken.length > 0) {
                            String authenticate = Base64.getEncoder().encodeToString(serverToken);
                            response.setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE + " " + authenticate);
                        }
                        if (!gssContext.isEstablished()) {
                            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                            LOG.trace("SPNEGO in progress");
                        } else {
                            String clientPrincipal = gssContext.getSrcName().toString();
                            KerberosName kerberosName = new KerberosName(clientPrincipal);
                            String userName = kerberosName.getShortName();
                            token = new AuthenticationToken(userName, clientPrincipal, getType());
                            response.setStatus(HttpServletResponse.SC_OK);
                            LOG.trace("SPNEGO completed for principal [{}]", clientPrincipal);
                        }
                    } finally {
                        if (gssContext != null) {
                            gssContext.dispose();
                        }
                        if (gssCreds != null) {
                            gssCreds.dispose();
                        }
                    }
                    return token;
                }
            });
        } catch (PrivilegedActionException ex) {
            if (ex.getException() instanceof IOException) {
                throw (IOException) ex.getException();
            } else {
                throw new AuthenticationException(ex.getException());
            }
        }
    }
    return token;
}
Also used : GSSCredential(org.ietf.jgss.GSSCredential) PrivilegedActionException(java.security.PrivilegedActionException) AuthenticationException(com.hortonworks.registries.auth.client.AuthenticationException) GSSContext(org.ietf.jgss.GSSContext) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) Oid(org.ietf.jgss.Oid) KerberosName(com.hortonworks.registries.auth.util.KerberosName) IOException(java.io.IOException)

Example 8 with AuthenticationException

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

the class AuthToken method split.

/**
 * Splits the string representation of a token into attributes pairs.
 *
 * @param tokenStr string representation of a token.
 *
 * @return a map with the attribute pairs of the token.
 *
 * @throws AuthenticationException thrown if the string representation of the token could not be broken into
 * attribute pairs.
 */
private static Map<String, String> split(String tokenStr) throws AuthenticationException {
    Map<String, String> map = new HashMap<String, String>();
    StringTokenizer st = new StringTokenizer(tokenStr, ATTR_SEPARATOR);
    while (st.hasMoreTokens()) {
        String part = st.nextToken();
        int separator = part.indexOf('=');
        if (separator == -1) {
            throw new AuthenticationException("Invalid authentication token");
        }
        String key = part.substring(0, separator);
        String value = part.substring(separator + 1);
        map.put(key, value);
    }
    return map;
}
Also used : StringTokenizer(java.util.StringTokenizer) HashMap(java.util.HashMap) AuthenticationException(com.hortonworks.registries.auth.client.AuthenticationException)

Example 9 with AuthenticationException

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

the class TestAuthenticationFilter method testGetTokenInvalidType.

@Test
public void testGetTokenInvalidType() throws Exception {
    AuthenticationFilter filter = new AuthenticationFilter();
    try {
        FilterConfig config = Mockito.mock(FilterConfig.class);
        Mockito.when(config.getInitParameter("management.operation.return")).thenReturn("true");
        Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn(DummyAuthenticationHandler.class.getName());
        Mockito.when(config.getInitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn("secret");
        Mockito.when(config.getInitParameterNames()).thenReturn(new Vector<String>(Arrays.asList(AuthenticationFilter.AUTH_TYPE, AuthenticationFilter.SIGNATURE_SECRET, "management.operation.return")).elements());
        getMockedServletContextWithStringSigner(config);
        filter.init(config);
        AuthenticationToken token = new AuthenticationToken("u", "p", "invalidtype");
        token.setExpires(System.currentTimeMillis() + TOKEN_VALIDITY_SEC);
        SignerSecretProvider secretProvider = StringSignerSecretProviderCreator.newStringSignerSecretProvider();
        Properties secretProviderProps = new Properties();
        secretProviderProps.setProperty(AuthenticationFilter.SIGNATURE_SECRET, "secret");
        secretProvider.init(secretProviderProps, null, TOKEN_VALIDITY_SEC);
        Signer signer = new Signer(secretProvider);
        String tokenSigned = signer.sign(token.toString());
        Cookie cookie = new Cookie(AuthenticatedURL.AUTH_COOKIE, tokenSigned);
        HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
        Mockito.when(request.getCookies()).thenReturn(new Cookie[] { cookie });
        boolean failed = false;
        try {
            filter.getToken(request);
        } catch (AuthenticationException ex) {
            Assert.assertEquals("Invalid AuthenticationToken type", ex.getMessage());
            failed = true;
        } finally {
            Assert.assertTrue("token not invalid type", failed);
        }
    } finally {
        filter.destroy();
    }
}
Also used : HttpCookie(java.net.HttpCookie) Cookie(javax.servlet.http.Cookie) SignerSecretProvider(com.hortonworks.registries.auth.util.SignerSecretProvider) AuthenticationException(com.hortonworks.registries.auth.client.AuthenticationException) Properties(java.util.Properties) Signer(com.hortonworks.registries.auth.util.Signer) HttpServletRequest(javax.servlet.http.HttpServletRequest) FilterConfig(javax.servlet.FilterConfig) Vector(java.util.Vector) Test(org.junit.Test)

Example 10 with AuthenticationException

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

the class TestJWTAuthenticationHandler method testFailedSignatureValidationJWT.

@Test
public void testFailedSignatureValidationJWT() throws Exception {
    try {
        // Create a public key that doesn't match the one needed to
        // verify the signature - in order to make it fail verification...
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(2048);
        KeyPair kp = kpg.genKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) kp.getPublic();
        handler.setPublicKey(publicKey);
        Properties props = getProperties();
        handler.init(props);
        SignedJWT jwt = getJWT("bob", new Date(new Date().getTime() + 5000), privateKey);
        Cookie cookie = new Cookie("hadoop-jwt", jwt.serialize());
        HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
        Mockito.when(request.getCookies()).thenReturn(new Cookie[] { cookie });
        Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer(SERVICE_URL));
        HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
        Mockito.when(response.encodeRedirectURL(SERVICE_URL)).thenReturn(SERVICE_URL);
        AuthenticationToken token = handler.alternateAuthenticate(request, response);
        Mockito.verify(response).sendRedirect(REDIRECT_LOCATION);
    } catch (ServletException se) {
        fail("alternateAuthentication should NOT have thrown a ServletException");
    } catch (AuthenticationException ae) {
        fail("alternateAuthentication should NOT have thrown a AuthenticationException");
    }
}
Also used : Cookie(javax.servlet.http.Cookie) KeyPair(java.security.KeyPair) AuthenticationException(com.hortonworks.registries.auth.client.AuthenticationException) HttpServletResponse(javax.servlet.http.HttpServletResponse) KeyPairGenerator(java.security.KeyPairGenerator) SignedJWT(com.nimbusds.jwt.SignedJWT) Properties(java.util.Properties) Date(java.util.Date) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) RSAPublicKey(java.security.interfaces.RSAPublicKey) Test(org.junit.Test)

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