Search in sources :

Example 1 with JWTToken

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

the class AccessTokenFederationFilter method doFilter.

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    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);
        }
        boolean verified = false;
        try {
            verified = authority.verifyToken(token);
        } catch (TokenServiceException e) {
            log.unableToVerifyToken(e);
        }
        if (verified) {
            long expires = Long.parseLong(token.getExpires());
            if (expires > System.currentTimeMillis()) {
                if (((HttpServletRequest) request).getRequestURL().indexOf(token.getAudience().toLowerCase()) != -1) {
                    Subject subject = createSubjectFromToken(token);
                    continueWithEstablishedSecurityContext(subject, (HttpServletRequest) request, (HttpServletResponse) response, chain);
                } else {
                    log.failedToValidateAudience();
                    sendUnauthorized(response);
                    // break the chain
                    return;
                }
            } else {
                log.tokenHasExpired();
                sendUnauthorized(response);
                // break the chain
                return;
            }
        } else {
            log.failedToVerifyTokenSignature();
            sendUnauthorized(response);
            // break the chain
            return;
        }
    } else {
        log.missingBearerToken();
        sendUnauthorized(response);
        // break the chain
        return;
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) 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)

Example 2 with JWTToken

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

the class JWTFederationFilter method doFilter.

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    String header = ((HttpServletRequest) request).getHeader("Authorization");
    String wireToken = null;
    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
        wireToken = header.substring(BEARER.length());
    } else {
        // check for query param
        wireToken = ((HttpServletRequest) request).getParameter(paramName);
    }
    if (wireToken != null) {
        try {
            JWT token = new JWTToken(wireToken);
            if (validateToken((HttpServletRequest) request, (HttpServletResponse) response, chain, token)) {
                Subject subject = createSubjectFromToken(token);
                continueWithEstablishedSecurityContext(subject, (HttpServletRequest) request, (HttpServletResponse) response, chain);
            }
        } catch (ParseException ex) {
            ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
    } else {
        // no token provided in header
        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) JWT(org.apache.knox.gateway.services.security.token.impl.JWT) HttpServletResponse(javax.servlet.http.HttpServletResponse) ParseException(java.text.ParseException) JWTToken(org.apache.knox.gateway.services.security.token.impl.JWTToken) Subject(javax.security.auth.Subject)

Example 3 with JWTToken

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

the class SSOCookieFederationFilter method doFilter.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    String wireToken = null;
    HttpServletRequest req = (HttpServletRequest) request;
    String loginURL = constructLoginURL(req);
    wireToken = getJWTFromCookie(req);
    if (wireToken == null) {
        if (req.getMethod().equals("OPTIONS")) {
            // CORS preflight requests to determine allowed origins and related config
            // must be able to continue without being redirected
            Subject sub = new Subject();
            sub.getPrincipals().add(new PrimaryPrincipal("anonymous"));
            continueWithEstablishedSecurityContext(sub, req, (HttpServletResponse) response, chain);
        }
        log.sendRedirectToLoginURL(loginURL);
        ((HttpServletResponse) response).sendRedirect(loginURL);
    } else {
        try {
            JWT token = new JWTToken(wireToken);
            if (validateToken((HttpServletRequest) request, (HttpServletResponse) response, chain, token)) {
                Subject subject = createSubjectFromToken(token);
                continueWithEstablishedSecurityContext(subject, (HttpServletRequest) request, (HttpServletResponse) response, chain);
            }
        } catch (ParseException ex) {
            ((HttpServletResponse) response).sendRedirect(loginURL);
        }
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) PrimaryPrincipal(org.apache.knox.gateway.security.PrimaryPrincipal) JWT(org.apache.knox.gateway.services.security.token.impl.JWT) HttpServletResponse(javax.servlet.http.HttpServletResponse) ParseException(java.text.ParseException) JWTToken(org.apache.knox.gateway.services.security.token.impl.JWTToken) Subject(javax.security.auth.Subject)

Example 4 with JWTToken

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

the class TokenServiceResourceTest method testDefaultTTL.

@Test
public void testDefaultTTL() throws Exception {
    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
    EasyMock.expect(context.getInitParameter("knox.token.audiences")).andReturn("recipient1,recipient2");
    EasyMock.expect(context.getInitParameter("knox.token.ttl")).andReturn(null);
    EasyMock.expect(context.getInitParameter("knox.token.target.url")).andReturn(null);
    EasyMock.expect(context.getInitParameter("knox.token.client.data")).andReturn(null);
    HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
    EasyMock.expect(request.getServletContext()).andReturn(context).anyTimes();
    Principal principal = EasyMock.createNiceMock(Principal.class);
    EasyMock.expect(principal.getName()).andReturn("alice").anyTimes();
    EasyMock.expect(request.getUserPrincipal()).andReturn(principal).anyTimes();
    GatewayServices services = EasyMock.createNiceMock(GatewayServices.class);
    EasyMock.expect(context.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE)).andReturn(services);
    JWTokenAuthority authority = new TestJWTokenAuthority(publicKey, privateKey);
    EasyMock.expect(services.getService(GatewayServices.TOKEN_SERVICE)).andReturn(authority);
    StringWriter writer = new StringWriter();
    PrintWriter printWriter = new PrintWriter(writer);
    HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
    EasyMock.expect(response.getWriter()).andReturn(printWriter);
    EasyMock.replay(principal, services, context, request, response);
    TokenResource tr = new TokenResource();
    tr.request = request;
    tr.response = response;
    tr.context = context;
    tr.init();
    // Issue a token
    Response retResponse = tr.doGet();
    assertEquals(200, retResponse.getStatus());
    // Parse the response
    String retString = writer.toString();
    String accessToken = getTagValue(retString, "access_token");
    assertNotNull(accessToken);
    String expiry = getTagValue(retString, "expires_in");
    assertNotNull(expiry);
    // Verify the token
    JWT parsedToken = new JWTToken(accessToken);
    assertEquals("alice", parsedToken.getSubject());
    assertTrue(authority.verifyToken(parsedToken));
    Date expiresDate = parsedToken.getExpiresDate();
    Date now = new Date();
    assertTrue(expiresDate.after(now));
    assertTrue((expiresDate.getTime() - now.getTime()) < 30000L);
}
Also used : GatewayServices(org.apache.knox.gateway.services.GatewayServices) TokenResource(org.apache.knox.gateway.service.knoxtoken.TokenResource) JWT(org.apache.knox.gateway.services.security.token.impl.JWT) HttpServletResponse(javax.servlet.http.HttpServletResponse) JWTToken(org.apache.knox.gateway.services.security.token.impl.JWTToken) Date(java.util.Date) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(javax.ws.rs.core.Response) StringWriter(java.io.StringWriter) JWTokenAuthority(org.apache.knox.gateway.services.security.token.JWTokenAuthority) ServletContext(javax.servlet.ServletContext) PrimaryPrincipal(org.apache.knox.gateway.security.PrimaryPrincipal) Principal(java.security.Principal) PrintWriter(java.io.PrintWriter) Test(org.junit.Test)

Example 5 with JWTToken

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

the class TokenServiceResourceTest method testOverflowTTL.

@Test
public void testOverflowTTL() throws Exception {
    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
    EasyMock.expect(context.getInitParameter("knox.token.audiences")).andReturn("recipient1,recipient2");
    EasyMock.expect(context.getInitParameter("knox.token.ttl")).andReturn(String.valueOf(Long.MAX_VALUE));
    EasyMock.expect(context.getInitParameter("knox.token.target.url")).andReturn(null);
    EasyMock.expect(context.getInitParameter("knox.token.client.data")).andReturn(null);
    HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
    EasyMock.expect(request.getServletContext()).andReturn(context).anyTimes();
    Principal principal = EasyMock.createNiceMock(Principal.class);
    EasyMock.expect(principal.getName()).andReturn("alice").anyTimes();
    EasyMock.expect(request.getUserPrincipal()).andReturn(principal).anyTimes();
    GatewayServices services = EasyMock.createNiceMock(GatewayServices.class);
    EasyMock.expect(context.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE)).andReturn(services);
    JWTokenAuthority authority = new TestJWTokenAuthority(publicKey, privateKey);
    EasyMock.expect(services.getService(GatewayServices.TOKEN_SERVICE)).andReturn(authority);
    StringWriter writer = new StringWriter();
    PrintWriter printWriter = new PrintWriter(writer);
    HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
    EasyMock.expect(response.getWriter()).andReturn(printWriter);
    EasyMock.replay(principal, services, context, request, response);
    TokenResource tr = new TokenResource();
    tr.request = request;
    tr.response = response;
    tr.context = context;
    tr.init();
    // Issue a token
    Response retResponse = tr.doGet();
    assertEquals(200, retResponse.getStatus());
    // Parse the response
    String retString = writer.toString();
    String accessToken = getTagValue(retString, "access_token");
    assertNotNull(accessToken);
    String expiry = getTagValue(retString, "expires_in");
    assertNotNull(expiry);
    // Verify the token
    JWT parsedToken = new JWTToken(accessToken);
    assertEquals("alice", parsedToken.getSubject());
    assertTrue(authority.verifyToken(parsedToken));
    Date expiresDate = parsedToken.getExpiresDate();
    Date now = new Date();
    assertTrue(expiresDate.after(now));
    assertTrue((expiresDate.getTime() - now.getTime()) < 30000L);
}
Also used : GatewayServices(org.apache.knox.gateway.services.GatewayServices) TokenResource(org.apache.knox.gateway.service.knoxtoken.TokenResource) JWT(org.apache.knox.gateway.services.security.token.impl.JWT) HttpServletResponse(javax.servlet.http.HttpServletResponse) JWTToken(org.apache.knox.gateway.services.security.token.impl.JWTToken) Date(java.util.Date) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(javax.ws.rs.core.Response) StringWriter(java.io.StringWriter) JWTokenAuthority(org.apache.knox.gateway.services.security.token.JWTokenAuthority) ServletContext(javax.servlet.ServletContext) PrimaryPrincipal(org.apache.knox.gateway.security.PrimaryPrincipal) Principal(java.security.Principal) PrintWriter(java.io.PrintWriter) Test(org.junit.Test)

Aggregations

JWTToken (org.apache.knox.gateway.services.security.token.impl.JWTToken)22 HttpServletRequest (javax.servlet.http.HttpServletRequest)21 HttpServletResponse (javax.servlet.http.HttpServletResponse)20 JWT (org.apache.knox.gateway.services.security.token.impl.JWT)19 Principal (java.security.Principal)17 ServletContext (javax.servlet.ServletContext)17 GatewayServices (org.apache.knox.gateway.services.GatewayServices)17 JWTokenAuthority (org.apache.knox.gateway.services.security.token.JWTokenAuthority)17 Test (org.junit.Test)17 PrimaryPrincipal (org.apache.knox.gateway.security.PrimaryPrincipal)10 PrintWriter (java.io.PrintWriter)9 StringWriter (java.io.StringWriter)9 Response (javax.ws.rs.core.Response)9 TokenResource (org.apache.knox.gateway.service.knoxtoken.TokenResource)9 Date (java.util.Date)8 ServletOutputStream (javax.servlet.ServletOutputStream)8 Cookie (javax.servlet.http.Cookie)8 ParseException (java.text.ParseException)4 Subject (javax.security.auth.Subject)4 TokenServiceException (org.apache.knox.gateway.services.security.token.TokenServiceException)3