Search in sources :

Example 31 with JwtToken

use of org.apache.cxf.rs.security.jose.jwt.JwtToken in project cxf by apache.

the class IssueJWTUnitTest method testIssueJWTToken.

/**
 * Test to successfully issue a JWT Token
 */
@org.junit.Test
public void testIssueJWTToken() throws Exception {
    TokenIssueOperation issueOperation = new TokenIssueOperation();
    issueOperation.setTokenStore(tokenStore);
    // Add Token Provider
    List<TokenProvider> providerList = new ArrayList<>();
    providerList.add(new JWTTokenProvider());
    issueOperation.setTokenProviders(providerList);
    // Add Service
    ServiceMBean service = new StaticService();
    service.setEndpoints(Collections.singletonList("http://dummy-service.com/dummy"));
    issueOperation.setServices(Collections.singletonList(service));
    // Add STSProperties object
    STSPropertiesMBean stsProperties = new StaticSTSProperties();
    Crypto crypto = CryptoFactory.getInstance(getEncryptionProperties());
    stsProperties.setEncryptionCrypto(crypto);
    stsProperties.setSignatureCrypto(crypto);
    stsProperties.setEncryptionUsername("myservicekey");
    stsProperties.setSignatureUsername("mystskey");
    stsProperties.setCallbackHandler(new PasswordCallbackHandler());
    stsProperties.setIssuer("STS");
    issueOperation.setStsProperties(stsProperties);
    // Mock up a request
    RequestSecurityTokenType request = new RequestSecurityTokenType();
    JAXBElement<String> tokenType = new JAXBElement<String>(QNameConstants.TOKEN_TYPE, String.class, JWTTokenProvider.JWT_TOKEN_TYPE);
    request.getAny().add(tokenType);
    request.getAny().add(createAppliesToElement("http://dummy-service.com/dummy"));
    // Mock up message context
    MessageImpl msg = new MessageImpl();
    WrappedMessageContext msgCtx = new WrappedMessageContext(msg);
    Principal principal = new CustomTokenPrincipal("alice");
    msgCtx.put(SecurityContext.class.getName(), createSecurityContext(principal));
    // Issue a token
    RequestSecurityTokenResponseCollectionType response = issueOperation.issue(request, principal, msgCtx);
    List<RequestSecurityTokenResponseType> securityTokenResponse = response.getRequestSecurityTokenResponse();
    assertTrue(!securityTokenResponse.isEmpty());
    // Test the generated token.
    Element token = null;
    for (Object tokenObject : securityTokenResponse.get(0).getAny()) {
        if (tokenObject instanceof JAXBElement<?> && REQUESTED_SECURITY_TOKEN.equals(((JAXBElement<?>) tokenObject).getName())) {
            RequestedSecurityTokenType rstType = (RequestedSecurityTokenType) ((JAXBElement<?>) tokenObject).getValue();
            token = (Element) rstType.getAny();
            break;
        }
    }
    assertNotNull(token);
    // Validate the token
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token.getTextContent());
    JwtToken jwt = jwtConsumer.getJwtToken();
    Assert.assertEquals("alice", jwt.getClaim(JwtConstants.CLAIM_SUBJECT));
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias(stsProperties.getSignatureUsername());
    X509Certificate[] certs = crypto.getX509Certificates(cryptoType);
    assertNotNull(certs);
    assertTrue(jwtConsumer.verifySignatureWith(certs[0], SignatureAlgorithm.RS256));
}
Also used : ServiceMBean(org.apache.cxf.sts.service.ServiceMBean) RequestSecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenType) JAXBElement(javax.xml.bind.JAXBElement) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) RequestSecurityTokenResponseType(org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseType) StaticSTSProperties(org.apache.cxf.sts.StaticSTSProperties) RequestedSecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.RequestedSecurityTokenType) StaticService(org.apache.cxf.sts.service.StaticService) RequestSecurityTokenResponseCollectionType(org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseCollectionType) CustomTokenPrincipal(org.apache.wss4j.common.principal.CustomTokenPrincipal) TokenProvider(org.apache.cxf.sts.token.provider.TokenProvider) JWTTokenProvider(org.apache.cxf.sts.token.provider.jwt.JWTTokenProvider) PasswordCallbackHandler(org.apache.cxf.sts.common.PasswordCallbackHandler) JwsJwtCompactConsumer(org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer) JWTTokenProvider(org.apache.cxf.sts.token.provider.jwt.JWTTokenProvider) JAXBElement(javax.xml.bind.JAXBElement) CryptoType(org.apache.wss4j.common.crypto.CryptoType) X509Certificate(java.security.cert.X509Certificate) JwtToken(org.apache.cxf.rs.security.jose.jwt.JwtToken) Crypto(org.apache.wss4j.common.crypto.Crypto) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) WrappedMessageContext(org.apache.cxf.jaxws.context.WrappedMessageContext) SecurityContext(org.apache.cxf.security.SecurityContext) MessageImpl(org.apache.cxf.message.MessageImpl) CustomTokenPrincipal(org.apache.wss4j.common.principal.CustomTokenPrincipal) Principal(java.security.Principal)

Example 32 with JwtToken

use of org.apache.cxf.rs.security.jose.jwt.JwtToken in project cxf by apache.

the class ValidateJWTTransformationTest method testSAMLToJWTTransformation.

@org.junit.Test
public void testSAMLToJWTTransformation() throws Exception {
    TokenValidateOperation validateOperation = new TokenValidateOperation();
    // Add Token Validator
    List<TokenValidator> validatorList = new ArrayList<>();
    validatorList.add(new SAMLTokenValidator());
    validateOperation.setTokenValidators(validatorList);
    // Add Token Provider
    List<TokenProvider> providerList = new ArrayList<>();
    providerList.add(new JWTTokenProvider());
    validateOperation.setTokenProviders(providerList);
    // Add STSProperties object
    STSPropertiesMBean stsProperties = new StaticSTSProperties();
    Crypto crypto = CryptoFactory.getInstance(getEncryptionProperties());
    stsProperties.setEncryptionCrypto(crypto);
    stsProperties.setSignatureCrypto(crypto);
    stsProperties.setEncryptionUsername("myservicekey");
    stsProperties.setSignatureUsername("mystskey");
    stsProperties.setCallbackHandler(new PasswordCallbackHandler());
    stsProperties.setIssuer("STS");
    validateOperation.setStsProperties(stsProperties);
    // Mock up a request
    RequestSecurityTokenType request = new RequestSecurityTokenType();
    JAXBElement<String> tokenType = new JAXBElement<String>(QNameConstants.TOKEN_TYPE, String.class, JWTTokenProvider.JWT_TOKEN_TYPE);
    request.getAny().add(tokenType);
    // Create a SAML Token
    Element samlToken = createSAMLAssertion(WSS4JConstants.WSS_SAML2_TOKEN_TYPE, crypto, "mystskey", new PasswordCallbackHandler());
    Document doc = samlToken.getOwnerDocument();
    samlToken = (Element) doc.appendChild(samlToken);
    ValidateTargetType validateTarget = new ValidateTargetType();
    validateTarget.setAny(samlToken);
    JAXBElement<ValidateTargetType> validateTargetType = new JAXBElement<ValidateTargetType>(QNameConstants.VALIDATE_TARGET, ValidateTargetType.class, validateTarget);
    request.getAny().add(validateTargetType);
    // Mock up message context
    MessageImpl msg = new MessageImpl();
    WrappedMessageContext msgCtx = new WrappedMessageContext(msg);
    Principal principal = new CustomTokenPrincipal("alice");
    msgCtx.put(SecurityContext.class.getName(), createSecurityContext(principal));
    // Validate a token
    RequestSecurityTokenResponseType response = validateOperation.validate(request, principal, msgCtx);
    assertTrue(validateResponse(response));
    // Test the generated token.
    Element token = null;
    for (Object tokenObject : response.getAny()) {
        if (tokenObject instanceof JAXBElement<?> && REQUESTED_SECURITY_TOKEN.equals(((JAXBElement<?>) tokenObject).getName())) {
            RequestedSecurityTokenType rstType = (RequestedSecurityTokenType) ((JAXBElement<?>) tokenObject).getValue();
            token = (Element) rstType.getAny();
            break;
        }
    }
    assertNotNull(token);
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token.getTextContent());
    JwtToken jwt = jwtConsumer.getJwtToken();
    Assert.assertEquals("alice", jwt.getClaim(JwtConstants.CLAIM_SUBJECT));
}
Also used : RequestSecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenType) JAXBElement(javax.xml.bind.JAXBElement) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) RequestSecurityTokenResponseType(org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseType) StaticSTSProperties(org.apache.cxf.sts.StaticSTSProperties) RequestedSecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.RequestedSecurityTokenType) Document(org.w3c.dom.Document) CustomTokenPrincipal(org.apache.wss4j.common.principal.CustomTokenPrincipal) TokenProvider(org.apache.cxf.sts.token.provider.TokenProvider) JWTTokenProvider(org.apache.cxf.sts.token.provider.jwt.JWTTokenProvider) SAMLTokenProvider(org.apache.cxf.sts.token.provider.SAMLTokenProvider) JWTTokenValidator(org.apache.cxf.sts.token.validator.jwt.JWTTokenValidator) TokenValidator(org.apache.cxf.sts.token.validator.TokenValidator) SAMLTokenValidator(org.apache.cxf.sts.token.validator.SAMLTokenValidator) PasswordCallbackHandler(org.apache.cxf.sts.common.PasswordCallbackHandler) JwsJwtCompactConsumer(org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer) JWTTokenProvider(org.apache.cxf.sts.token.provider.jwt.JWTTokenProvider) JAXBElement(javax.xml.bind.JAXBElement) JwtToken(org.apache.cxf.rs.security.jose.jwt.JwtToken) Crypto(org.apache.wss4j.common.crypto.Crypto) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) WrappedMessageContext(org.apache.cxf.jaxws.context.WrappedMessageContext) SecurityContext(org.apache.cxf.security.SecurityContext) SAMLTokenValidator(org.apache.cxf.sts.token.validator.SAMLTokenValidator) ValidateTargetType(org.apache.cxf.ws.security.sts.provider.model.ValidateTargetType) MessageImpl(org.apache.cxf.message.MessageImpl) CustomTokenPrincipal(org.apache.wss4j.common.principal.CustomTokenPrincipal) Principal(java.security.Principal)

Example 33 with JwtToken

use of org.apache.cxf.rs.security.jose.jwt.JwtToken in project cxf by apache.

the class BigQueryServer method getAccessToken.

private static ClientAccessToken getAccessToken(PrivateKey privateKey, String issuer) {
    JwsHeaders headers = new JwsHeaders(JoseType.JWT, SignatureAlgorithm.RS256);
    JwtClaims claims = new JwtClaims();
    claims.setIssuer(issuer);
    claims.setAudience("https://www.googleapis.com/oauth2/v3/token");
    long issuedAt = OAuthUtils.getIssuedAt();
    claims.setIssuedAt(issuedAt);
    claims.setExpiryTime(issuedAt + 60 * 60);
    claims.setProperty("scope", "https://www.googleapis.com/auth/bigquery.readonly");
    JwtToken token = new JwtToken(headers, claims);
    JwsJwtCompactProducer p = new JwsJwtCompactProducer(token);
    String base64UrlAssertion = p.signWith(privateKey);
    JwtBearerGrant grant = new JwtBearerGrant(base64UrlAssertion);
    WebClient accessTokenService = WebClient.create("https://www.googleapis.com/oauth2/v3/token", Arrays.asList(new OAuthJSONProvider(), new AccessTokenGrantWriter()));
    WebClient.getConfig(accessTokenService).getInInterceptors().add(new LoggingInInterceptor());
    accessTokenService.type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_JSON);
    return accessTokenService.post(grant, ClientAccessToken.class);
}
Also used : JwtToken(org.apache.cxf.rs.security.jose.jwt.JwtToken) JwsHeaders(org.apache.cxf.rs.security.jose.jws.JwsHeaders) JwsJwtCompactProducer(org.apache.cxf.rs.security.jose.jws.JwsJwtCompactProducer) JwtClaims(org.apache.cxf.rs.security.jose.jwt.JwtClaims) JwtBearerGrant(org.apache.cxf.rs.security.oauth2.grants.jwt.JwtBearerGrant) AccessTokenGrantWriter(org.apache.cxf.rs.security.oauth2.client.AccessTokenGrantWriter) OAuthJSONProvider(org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider) LoggingInInterceptor(org.apache.cxf.interceptor.LoggingInInterceptor) WebClient(org.apache.cxf.jaxrs.client.WebClient)

Example 34 with JwtToken

use of org.apache.cxf.rs.security.jose.jwt.JwtToken in project cxf by apache.

the class AbstractJwtAuthenticationFilter method filter.

@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    String encodedJwtToken = getEncodedJwtToken(requestContext);
    JwtToken token = super.getJwtToken(encodedJwtToken);
    SecurityContext securityContext = configureSecurityContext(token);
    if (securityContext != null) {
        JAXRSUtils.getCurrentMessage().put(SecurityContext.class, securityContext);
    }
}
Also used : JwtToken(org.apache.cxf.rs.security.jose.jwt.JwtToken) SecurityContext(org.apache.cxf.security.SecurityContext)

Example 35 with JwtToken

use of org.apache.cxf.rs.security.jose.jwt.JwtToken in project cxf by apache.

the class JWTAlgorithmTest method testEncryptionDynamic.

@org.junit.Test
public void testEncryptionDynamic() throws Exception {
    URL busFile = JWTAlgorithmTest.class.getResource("client.xml");
    List<Object> providers = new ArrayList<>();
    providers.add(new JacksonJsonProvider());
    JwtAuthenticationClientFilter clientFilter = new JwtAuthenticationClientFilter();
    clientFilter.setJwsRequired(false);
    clientFilter.setJweRequired(true);
    providers.add(clientFilter);
    String address = "https://localhost:" + PORT + "/encryptedjwt/bookstore/books";
    WebClient client = WebClient.create(address, providers, busFile.toString());
    client.type("application/json").accept("application/json");
    // Create the JWT Token
    JwtClaims claims = new JwtClaims();
    claims.setSubject("alice");
    claims.setIssuer("DoubleItSTSIssuer");
    claims.setIssuedAt(Instant.now().getEpochSecond());
    claims.setAudiences(toList(address));
    JwtToken token = new JwtToken(claims);
    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.keystore.type", "jwk");
    properties.put("rs.security.keystore.alias", "2011-04-29");
    properties.put("rs.security.keystore.file", "org/apache/cxf/systest/jaxrs/security/certs/jwkPublicSet.txt");
    properties.put("rs.security.encryption.content.algorithm", "A128GCM");
    properties.put("rs.security.encryption.key.algorithm", "RSA-OAEP");
    properties.put(JwtConstants.JWT_TOKEN, token);
    WebClient.getConfig(client).getRequestContext().putAll(properties);
    Response response = client.post(new Book("book", 123L));
    assertEquals(response.getStatus(), 200);
    Book returnedBook = response.readEntity(Book.class);
    assertEquals(returnedBook.getName(), "book");
    assertEquals(returnedBook.getId(), 123L);
}
Also used : JwtClaims(org.apache.cxf.rs.security.jose.jwt.JwtClaims) HashMap(java.util.HashMap) JacksonJsonProvider(com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider) ArrayList(java.util.ArrayList) WebClient(org.apache.cxf.jaxrs.client.WebClient) URL(java.net.URL) JwtToken(org.apache.cxf.rs.security.jose.jwt.JwtToken) Response(javax.ws.rs.core.Response) Book(org.apache.cxf.systest.jaxrs.security.Book) JwtAuthenticationClientFilter(org.apache.cxf.rs.security.jose.jaxrs.JwtAuthenticationClientFilter)

Aggregations

JwtToken (org.apache.cxf.rs.security.jose.jwt.JwtToken)102 JwsJwtCompactConsumer (org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer)47 WebClient (org.apache.cxf.jaxrs.client.WebClient)42 JwtClaims (org.apache.cxf.rs.security.jose.jwt.JwtClaims)42 URL (java.net.URL)41 ArrayList (java.util.ArrayList)37 Response (javax.ws.rs.core.Response)35 JWTTokenProvider (org.apache.cxf.sts.token.provider.jwt.JWTTokenProvider)33 HashMap (java.util.HashMap)31 JacksonJsonProvider (com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider)28 JwtAuthenticationClientFilter (org.apache.cxf.rs.security.jose.jaxrs.JwtAuthenticationClientFilter)28 Book (org.apache.cxf.systest.jaxrs.security.Book)28 JAXBElement (javax.xml.bind.JAXBElement)13 Crypto (org.apache.wss4j.common.crypto.Crypto)13 Element (org.w3c.dom.Element)12 ClaimsHandler (org.apache.cxf.sts.claims.ClaimsHandler)10 ClaimsManager (org.apache.cxf.sts.claims.ClaimsManager)10 CustomClaimsHandler (org.apache.cxf.sts.common.CustomClaimsHandler)10 CustomTokenPrincipal (org.apache.wss4j.common.principal.CustomTokenPrincipal)10 TokenProvider (org.apache.cxf.sts.token.provider.TokenProvider)9