Java Code Examples for org.apache.cxf.rs.security.jose.jwt.JwtUtils

The following examples show how to use org.apache.cxf.rs.security.jose.jwt.JwtUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: cxf   Source File: JwtBearerAuthHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void validateToken(JwtToken jwt) {
    super.validateToken(jwt);

    // We must have an issuer
    if (jwt.getClaim(JwtConstants.CLAIM_ISSUER) == null) {
        throw new OAuthServiceException(OAuthConstants.INVALID_GRANT);
    }

    // We must have a Subject
    if (jwt.getClaim(JwtConstants.CLAIM_SUBJECT) == null) {
        throw new OAuthServiceException(OAuthConstants.INVALID_GRANT);
    }

    // We must have an Expiry
    if (jwt.getClaim(JwtConstants.CLAIM_EXPIRY) == null) {
        throw new OAuthServiceException(OAuthConstants.INVALID_GRANT);
    }

    JwtUtils.validateTokenClaims(jwt.getClaims(), getTtl(), getClockOffset(), isValidateAudience());
}
 
Example 2
Source Project: cxf   Source File: OidcRpAuthenticationFilter.java    License: Apache License 2.0 6 votes vote down vote up
protected boolean checkSecurityContext(ContainerRequestContext rc) {
    OidcClientTokenContext tokenContext = (OidcClientTokenContext)stateManager.getClientTokenContext(mc);
    if (tokenContext == null) {
        return false;
    }
    IdToken idToken = tokenContext.getIdToken();
    try {
        // If ID token has expired then the context is no longer valid
        JwtUtils.validateJwtExpiry(idToken, 0, idToken.getExpiryTime() != null);
    } catch (JwtException ex) {
        stateManager.removeClientTokenContext(new MessageContextImpl(JAXRSUtils.getCurrentMessage()));
        return false;
    }
    OidcClientTokenContextImpl newTokenContext = new OidcClientTokenContextImpl();
    newTokenContext.setToken(tokenContext.getToken());
    newTokenContext.setIdToken(idToken);
    newTokenContext.setUserInfo(tokenContext.getUserInfo());
    newTokenContext.setState(toRequestState(rc));
    JAXRSUtils.getCurrentMessage().setContent(ClientTokenContext.class, newTokenContext);

    OidcSecurityContext oidcSecCtx = new OidcSecurityContext(newTokenContext);
    oidcSecCtx.setRoleClaim(roleClaim);
    rc.setSecurityContext(oidcSecCtx);
    return true;
}
 
Example 3
Source Project: cxf-fediz   Source File: TrustedIdpOIDCProtocolHandler.java    License: Apache License 2.0 6 votes vote down vote up
protected void validateToken(JwtToken jwt, String clientId) {
    // We must have the following claims
    if (jwt.getClaim(JwtConstants.CLAIM_ISSUER) == null
        || jwt.getClaim(JwtConstants.CLAIM_SUBJECT) == null
        || jwt.getClaim(JwtConstants.CLAIM_AUDIENCE) == null
        || jwt.getClaim(JwtConstants.CLAIM_EXPIRY) == null
        || jwt.getClaim(JwtConstants.CLAIM_ISSUED_AT) == null) {
        LOG.warn("The IdToken is missing a required claim");
        throw new IllegalStateException("The IdToken is missing a required claim");
    }

    // The audience must match the client_id of this client
    boolean match = false;
    for (String audience : jwt.getClaims().getAudiences()) {
        if (clientId.equals(audience)) {
            match = true;
            break;
        }
    }
    if (!match) {
        LOG.warn("The audience of the token does not match this client");
        throw new IllegalStateException("The audience of the token does not match this client");
    }

    JwtUtils.validateTokenClaims(jwt.getClaims(), 300, 0, false);
}
 
Example 4
private void validateClaims(JwtToken jwt) throws BadCredentialsException, JwtException {
	JwtClaims claims = jwt.getClaims();

	if (claims != null) {
		JwtUtils.validateJwtExpiry(claims, 0, false);
		JwtUtils.validateJwtNotBefore(claims, 0, false);
	}
}
 
Example 5
private String createJwt(SamlResponse samlResponse) throws Exception {
    JwtClaims jwtClaims = new JwtClaims();
    JwtToken jwt = new JwtToken(jwtClaims);

    jwtClaims.setNotBefore(System.currentTimeMillis() / 1000);
    jwtClaims.setExpiryTime(getJwtExpiration(samlResponse));

    jwtClaims.setProperty(this.jwtSubjectKey, this.extractSubject(samlResponse));

    if (this.samlSubjectKey != null) {
        jwtClaims.setProperty("saml_ni", samlResponse.getNameId());
    }

    if (samlResponse.getNameIdFormat() != null) {
        jwtClaims.setProperty("saml_nif", SamlNameIdFormat.getByUri(samlResponse.getNameIdFormat()).getShortName());
    }

    String sessionIndex = samlResponse.getSessionIndex();

    if (sessionIndex != null) {
        jwtClaims.setProperty("saml_si", sessionIndex);
    }

    if (this.samlRolesKey != null && this.jwtRolesKey != null) {
        String[] roles = this.extractRoles(samlResponse);

        jwtClaims.setProperty(this.jwtRolesKey, roles);
    }

    String encodedJwt = this.jwtProducer.processJwt(jwt);

    if (token_log.isDebugEnabled()) {
        token_log.debug("Created JWT: " + encodedJwt + "\n" + jsonMapReaderWriter.toJson(jwt.getJwsHeaders()) + "\n"
                + JwtUtils.claimsToJson(jwt.getClaims()));
    }

    return encodedJwt;
}
 
Example 6
Source Project: cxf   Source File: JAXRSOAuth2TlsTest.java    License: Apache License 2.0 5 votes vote down vote up
private void doTestTwoWayTLSClientIdBoundJwt(String clientId) throws Exception {
    String atServiceAddress = "https://localhost:" + PORT + "/oauth2Jwt/token";
    WebClient wc = createOAuth2WebClient(atServiceAddress);

    ClientAccessToken at = OAuthClientUtils.getAccessToken(wc, new Consumer(clientId),
                                                           new CustomGrant());
    assertNotNull(at.getTokenKey());
    JwsJwtCompactConsumer c = new JwsJwtCompactConsumer(at.getTokenKey());
    JwtClaims claims = JwtUtils.jsonToClaims(c.getDecodedJwsPayload());

    Map<String, Object> cnfs = claims.getMapProperty(JwtConstants.CLAIM_CONFIRMATION);
    assertNotNull(cnfs);
    assertNotNull(cnfs.get(JoseConstants.HEADER_X509_THUMBPRINT_SHA256));

    String protectedRsAddress = "https://localhost:" + PORT + "/rsJwt/bookstore/books/123";
    WebClient wcRs = createRsWebClient(protectedRsAddress, at, "client.xml");
    Book book = wcRs.get(Book.class);
    assertEquals(123L, book.getId());

    String protectedRsAddress2 = "https://localhost:" + PORT + "/rsJwt2/bookstore/books/123";
    WebClient wcRs2 = createRsWebClient(protectedRsAddress2, at, "client.xml");
    book = wcRs2.get(Book.class);
    assertEquals(123L, book.getId());

    String unprotectedRsAddress = "https://localhost:" + PORT + "/rsUnprotected/bookstore/books/123";
    WebClient wcRsDiffClientCert = createRsWebClient(unprotectedRsAddress, at, "client2.xml");
    // Unprotected resource
    book = wcRsDiffClientCert.get(Book.class);
    assertEquals(123L, book.getId());

    // Protected resource, access token was created with Morpit.jks key, RS is accessed with
    // Bethal.jks key, thus 401 is expected
    wcRsDiffClientCert = createRsWebClient(protectedRsAddress, at, "client2.xml");
    assertEquals(401, wcRsDiffClientCert.get().getStatus());
    wcRsDiffClientCert = createRsWebClient(protectedRsAddress2, at, "client2.xml");
    assertEquals(401, wcRsDiffClientCert.get().getStatus());
}
 
Example 7
Source Project: cxf   Source File: AbstractJwtHandler.java    License: Apache License 2.0 5 votes vote down vote up
protected void validateClaims(Client client, JwtClaims claims) {
    if (getAudience() != null) {
        JAXRSUtils.getCurrentMessage().put(JwtConstants.EXPECTED_CLAIM_AUDIENCE, getAudience());
    }
    JwtUtils.validateTokenClaims(claims, ttl, clockOffset, true);

    validateIssuer(claims.getIssuer());
    validateSubject(client, claims.getSubject());

    // We must have an Expiry
    if (claims.getClaim(JwtConstants.CLAIM_EXPIRY) == null) {
        throw new OAuthServiceException(OAuthConstants.INVALID_GRANT);
    }
}
 
Example 8
Source Project: cxf   Source File: JWTTokenValidator.java    License: Apache License 2.0 4 votes vote down vote up
protected void validateToken(JwtToken jwt) {
    JwtUtils.validateTokenClaims(jwt.getClaims(), ttl, clockOffset, false);
}
 
Example 9
Source Project: cxf   Source File: AbstractJwtAuthenticationFilter.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected void validateToken(JwtToken jwt) {
    JwtUtils.validateTokenClaims(jwt.getClaims(), getTtl(), getClockOffset(), isValidateAudience());
}
 
Example 10
Source Project: cxf   Source File: JwsJwtCompactProducer.java    License: Apache License 2.0 4 votes vote down vote up
protected JwsJwtCompactProducer(JwtToken token, JsonMapObjectReaderWriter w) {
    super(new JwsHeaders(token.getJwsHeaders()), w,
          JwtUtils.claimsToJson(token.getClaims(), w));
}
 
Example 11
Source Project: cxf   Source File: JweJwtCompactConsumer.java    License: Apache License 2.0 4 votes vote down vote up
public JwtToken decryptWith(JweDecryptionProvider jwe) {
    byte[] bytes = jwe.decrypt(jweConsumer.getJweDecryptionInput());
    JwtClaims claims = JwtUtils.jsonToClaims(new String(bytes, StandardCharsets.UTF_8));
    return new JwtToken(headers, claims);
}
 
Example 12
Source Project: cxf   Source File: JweJwtCompactProducer.java    License: Apache License 2.0 4 votes vote down vote up
public JweJwtCompactProducer(JweHeaders joseHeaders, JwtClaims claims) {
    super(joseHeaders, JwtUtils.claimsToJson(claims));
}
 
Example 13
Source Project: cxf   Source File: UserInfoService.java    License: Apache License 2.0 4 votes vote down vote up
protected Object convertUserInfoToResponseEntity(UserInfo userInfo) {
    // By default a JAX-RS MessageBodyWriter is expected to serialize UserInfo.
    return convertClearUserInfoToString ? JwtUtils.claimsToJson(userInfo) : userInfo;
}