Search in sources :

Example 6 with TokenServiceException

use of org.apache.knox.gateway.services.security.token.TokenServiceException in project knox by apache.

the class TokenResource method getAuthenticationToken.

private Response getAuthenticationToken() {
    if (clientCertRequired) {
        X509Certificate cert = extractCertificate(request);
        if (cert != null) {
            if (!allowedDNs.contains(cert.getSubjectDN().getName())) {
                return Response.status(403).entity("{ \"Unable to get token - untrusted client cert.\" }").build();
            }
        } else {
            return Response.status(403).entity("{ \"Unable to get token - client cert required.\" }").build();
        }
    }
    GatewayServices services = (GatewayServices) request.getServletContext().getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
    JWTokenAuthority ts = services.getService(GatewayServices.TOKEN_SERVICE);
    Principal p = ((HttpServletRequest) request).getUserPrincipal();
    long expires = getExpiry();
    try {
        JWT token = null;
        if (targetAudiences.isEmpty()) {
            token = ts.issueToken(p, signatureAlgorithm, expires);
        } else {
            token = ts.issueToken(p, targetAudiences, signatureAlgorithm, expires);
        }
        if (token != null) {
            String accessToken = token.toString();
            HashMap<String, Object> map = new HashMap<>();
            map.put(ACCESS_TOKEN, accessToken);
            map.put(TOKEN_TYPE, BEARER);
            map.put(EXPIRES_IN, expires);
            if (tokenTargetUrl != null) {
                map.put(TARGET_URL, tokenTargetUrl);
            }
            if (tokenClientDataMap != null) {
                map.putAll(tokenClientDataMap);
            }
            String jsonResponse = JsonUtils.renderAsJsonString(map);
            response.getWriter().write(jsonResponse);
            return Response.ok().build();
        } else {
            return Response.serverError().build();
        }
    } catch (TokenServiceException | IOException e) {
        log.unableToIssueToken(e);
    }
    return Response.ok().entity("{ \"Unable to acquire token.\" }").build();
}
Also used : GatewayServices(org.apache.knox.gateway.services.GatewayServices) HashMap(java.util.HashMap) JWT(org.apache.knox.gateway.services.security.token.impl.JWT) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) HttpServletRequest(javax.servlet.http.HttpServletRequest) JWTokenAuthority(org.apache.knox.gateway.services.security.token.JWTokenAuthority) Principal(java.security.Principal) TokenServiceException(org.apache.knox.gateway.services.security.token.TokenServiceException)

Example 7 with TokenServiceException

use of org.apache.knox.gateway.services.security.token.TokenServiceException in project knox by apache.

the class WebSSOResource method getAuthenticationToken.

private Response getAuthenticationToken(int statusCode) {
    GatewayServices services = (GatewayServices) request.getServletContext().getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
    boolean removeOriginalUrlCookie = true;
    String original = getCookieValue((HttpServletRequest) request, ORIGINAL_URL_COOKIE_NAME);
    if (original == null) {
        // in the case where there are no SAML redirects done before here
        // we need to get it from the request parameters
        removeOriginalUrlCookie = false;
        original = getOriginalUrlFromQueryParams();
        if (original.isEmpty()) {
            log.originalURLNotFound();
            throw new WebApplicationException("Original URL not found in the request.", Response.Status.BAD_REQUEST);
        }
        boolean validRedirect = RegExUtils.checkWhitelist(whitelist, original);
        if (!validRedirect) {
            log.whiteListMatchFail(original, whitelist);
            throw new WebApplicationException("Original URL not valid according to the configured whitelist.", Response.Status.BAD_REQUEST);
        }
    }
    JWTokenAuthority ts = services.getService(GatewayServices.TOKEN_SERVICE);
    Principal p = ((HttpServletRequest) request).getUserPrincipal();
    try {
        JWT token = null;
        if (targetAudiences.isEmpty()) {
            token = ts.issueToken(p, signatureAlgorithm, getExpiry());
        } else {
            token = ts.issueToken(p, targetAudiences, signatureAlgorithm, getExpiry());
        }
        // Coverity CID 1327959
        if (token != null) {
            addJWTHadoopCookie(original, token);
        }
        if (removeOriginalUrlCookie) {
            removeOriginalUrlCookie(response);
        }
        log.aboutToRedirectToOriginal(original);
        response.setStatus(statusCode);
        response.setHeader("Location", original);
        try {
            response.getOutputStream().close();
        } catch (IOException e) {
            log.unableToCloseOutputStream(e.getMessage(), Arrays.toString(e.getStackTrace()));
        }
    } catch (TokenServiceException e) {
        log.unableToIssueToken(e);
    }
    URI location = null;
    try {
        location = new URI(original);
    } catch (URISyntaxException urise) {
    // todo log return error response
    }
    if (!enableSession) {
        // invalidate the session to avoid autologin
        // Coverity CID 1352857
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }
    }
    return Response.seeOther(location).entity("{ \"redirectTo\" : " + original + " }").build();
}
Also used : GatewayServices(org.apache.knox.gateway.services.GatewayServices) WebApplicationException(javax.ws.rs.WebApplicationException) JWT(org.apache.knox.gateway.services.security.token.impl.JWT) HttpSession(javax.servlet.http.HttpSession) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) HttpServletRequest(javax.servlet.http.HttpServletRequest) JWTokenAuthority(org.apache.knox.gateway.services.security.token.JWTokenAuthority) Principal(java.security.Principal) TokenServiceException(org.apache.knox.gateway.services.security.token.TokenServiceException)

Example 8 with TokenServiceException

use of org.apache.knox.gateway.services.security.token.TokenServiceException in project knox by apache.

the class DefaultTokenAuthorityService method issueToken.

@Override
public JWT issueToken(Principal p, List<String> audiences, String algorithm, long expires) throws TokenServiceException {
    String[] claimArray = new String[4];
    claimArray[0] = "KNOXSSO";
    claimArray[1] = p.getName();
    claimArray[2] = null;
    if (expires == -1) {
        claimArray[3] = null;
    } else {
        claimArray[3] = String.valueOf(expires);
    }
    JWT token = null;
    if (SUPPORTED_SIG_ALGS.contains(algorithm)) {
        token = new JWTToken(algorithm, claimArray, audiences);
        RSAPrivateKey key;
        char[] passphrase = null;
        try {
            passphrase = getSigningKeyPassphrase();
        } catch (AliasServiceException e) {
            throw new TokenServiceException(e);
        }
        try {
            key = (RSAPrivateKey) ks.getSigningKey(getSigningKeyAlias(), passphrase);
            JWSSigner signer = new RSASSASigner(key);
            token.sign(signer);
        } catch (KeystoreServiceException e) {
            throw new TokenServiceException(e);
        }
    } else {
        throw new TokenServiceException("Cannot issue token - Unsupported algorithm");
    }
    return token;
}
Also used : JWT(org.apache.knox.gateway.services.security.token.impl.JWT) AliasServiceException(org.apache.knox.gateway.services.security.AliasServiceException) RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) KeystoreServiceException(org.apache.knox.gateway.services.security.KeystoreServiceException) JWTToken(org.apache.knox.gateway.services.security.token.impl.JWTToken) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) JWSSigner(com.nimbusds.jose.JWSSigner) TokenServiceException(org.apache.knox.gateway.services.security.token.TokenServiceException)

Example 9 with TokenServiceException

use of org.apache.knox.gateway.services.security.token.TokenServiceException in project knox by apache.

the class DefaultTokenAuthorityServiceTest method testTokenCreationBadSignatureAlgorithm.

@Test
public void testTokenCreationBadSignatureAlgorithm() throws Exception {
    Principal principal = EasyMock.createNiceMock(Principal.class);
    EasyMock.expect(principal.getName()).andReturn("john.doe@example.com");
    GatewayConfig config = EasyMock.createNiceMock(GatewayConfig.class);
    String basedir = System.getProperty("basedir");
    if (basedir == null) {
        basedir = new File(".").getCanonicalPath();
    }
    EasyMock.expect(config.getGatewaySecurityDir()).andReturn(basedir + "/target/test-classes");
    EasyMock.expect(config.getSigningKeystoreName()).andReturn("server-keystore.jks");
    EasyMock.expect(config.getSigningKeyAlias()).andReturn("server").anyTimes();
    MasterService ms = EasyMock.createNiceMock(MasterService.class);
    EasyMock.expect(ms.getMasterSecret()).andReturn("horton".toCharArray());
    AliasService as = EasyMock.createNiceMock(AliasService.class);
    EasyMock.expect(as.getGatewayIdentityPassphrase()).andReturn("horton".toCharArray());
    EasyMock.replay(principal, config, ms, as);
    KeystoreService ks = new DefaultKeystoreService();
    ((DefaultKeystoreService) ks).setMasterService(ms);
    ((DefaultKeystoreService) ks).init(config, new HashMap<String, String>());
    JWTokenAuthority ta = new DefaultTokenAuthorityService();
    ((DefaultTokenAuthorityService) ta).setAliasService(as);
    ((DefaultTokenAuthorityService) ta).setKeystoreService(ks);
    ((DefaultTokenAuthorityService) ta).init(config, new HashMap<String, String>());
    try {
        ta.issueToken(principal, "none");
        fail("Failure expected on a bad signature algorithm");
    } catch (TokenServiceException ex) {
    // expected
    }
}
Also used : AliasService(org.apache.knox.gateway.services.security.AliasService) DefaultKeystoreService(org.apache.knox.gateway.services.security.impl.DefaultKeystoreService) JWTokenAuthority(org.apache.knox.gateway.services.security.token.JWTokenAuthority) DefaultKeystoreService(org.apache.knox.gateway.services.security.impl.DefaultKeystoreService) KeystoreService(org.apache.knox.gateway.services.security.KeystoreService) File(java.io.File) MasterService(org.apache.knox.gateway.services.security.MasterService) Principal(java.security.Principal) TokenServiceException(org.apache.knox.gateway.services.security.token.TokenServiceException) GatewayConfig(org.apache.knox.gateway.config.GatewayConfig) Test(org.junit.Test)

Example 10 with TokenServiceException

use of org.apache.knox.gateway.services.security.token.TokenServiceException in project knox by apache.

the class JWTAccessTokenAssertionFilter method doFilter.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    String jsonResponse = null;
    String header = ((HttpServletRequest) request).getHeader("Authorization");
    if (header != null && header.startsWith(BEARER)) {
        // what follows the bearer designator should be the JWT token being used to request or as an access token
        String wireToken = header.substring(BEARER.length());
        JWTToken token;
        try {
            token = JWTToken.parseToken(wireToken);
        } catch (ParseException e) {
            throw new ServletException("ParseException encountered while processing the JWT token: ", e);
        }
        // ensure that there is a valid jwt token available and that there isn't a misconfiguration of filters
        if (token != null) {
            try {
                authority.verifyToken(token);
            } catch (TokenServiceException e) {
                log.unableToVerifyToken(e);
            }
        } else {
            throw new ServletException("Expected JWT Token not provided as Bearer token");
        }
        // authorization of the user for the requested service (and resource?) should have been done by
        // the JWTFederationFilter - once we get here we can assume that it is authorized and we just need
        // to assert the identity via an access token
        Subject subject = Subject.getSubject(AccessController.getContext());
        String principalName = getPrincipalName(subject);
        principalName = mapper.mapUserPrincipal(principalName);
        // calculate expiration timestamp: validity * 1000 + currentTimeInMillis
        long expires = System.currentTimeMillis() + validity * 1000;
        String serviceName = request.getParameter("service-name");
        String clusterName = request.getParameter("cluster-name");
        String accessToken = getAccessToken(principalName, serviceName, expires);
        String serviceURL = sr.lookupServiceURL(clusterName, serviceName);
        HashMap<String, Object> map = new HashMap<>();
        // TODO: populate map from JWT authorization code
        map.put(ACCESS_TOKEN, accessToken);
        map.put(TOKEN_TYPE, BEARER);
        map.put(EXPIRES_IN, expires);
        // TODO: this url needs to be rewritten when in gateway deployments....
        map.put(SVC_URL, serviceURL);
        jsonResponse = JsonUtils.renderAsJsonString(map);
        response.getWriter().write(jsonResponse);
        // break filter chain
        return;
    } else {
        // no token provided in header
        // something is really wrong since the JWTFederationFilter should have verified its existence already
        // TODO: may have to check cookie and url as well before sending error
        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
        // break filter chain
        return;
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) HashMap(java.util.HashMap) HttpServletResponse(javax.servlet.http.HttpServletResponse) ParseException(java.text.ParseException) JWTToken(org.apache.knox.gateway.services.security.token.impl.JWTToken) TokenServiceException(org.apache.knox.gateway.services.security.token.TokenServiceException) Subject(javax.security.auth.Subject)

Aggregations

TokenServiceException (org.apache.knox.gateway.services.security.token.TokenServiceException)10 JWT (org.apache.knox.gateway.services.security.token.impl.JWT)5 Principal (java.security.Principal)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 ParseException (java.text.ParseException)3 HashMap (java.util.HashMap)3 Subject (javax.security.auth.Subject)3 JWTokenAuthority (org.apache.knox.gateway.services.security.token.JWTokenAuthority)3 JWTToken (org.apache.knox.gateway.services.security.token.impl.JWTToken)3 IOException (java.io.IOException)2 ServletException (javax.servlet.ServletException)2 GatewayServices (org.apache.knox.gateway.services.GatewayServices)2 KeystoreServiceException (org.apache.knox.gateway.services.security.KeystoreServiceException)2 JWSSigner (com.nimbusds.jose.JWSSigner)1 JWSVerifier (com.nimbusds.jose.JWSVerifier)1 RSASSASigner (com.nimbusds.jose.crypto.RSASSASigner)1 RSASSAVerifier (com.nimbusds.jose.crypto.RSASSAVerifier)1 File (java.io.File)1 URI (java.net.URI)1 URISyntaxException (java.net.URISyntaxException)1