Search in sources :

Example 6 with JwtClaimsSet

use of org.forgerock.json.jose.jwt.JwtClaimsSet in project OpenAM by OpenRock.

the class JwtSessionMapper method asJwt.

/**
     * Store the SessionInfo as a serialized_session claim in a JWT.
     *
     * The returned JWT will be signed using the specified {@link JwsAlgorithm}.
     *
     * @param sessionInfo Non-null, SessionInfo state to be stored in the returned JWT.
     *
     * @return String JWT with SessionInfo stored in serialized_session claim.
     */
public String asJwt(@Nonnull SessionInfo sessionInfo) {
    Reject.ifNull(sessionInfo, "sessionInfo must not ne null.");
    String json = asJson(sessionInfo);
    // TODO: Make serialized_session value actual JSON rather than a String
    JwtClaimsSet claimsSet = jwtBuilderFactory.claims().claim(SERIALIZED_SESSION_CLAIM, json).build();
    if (encryptionKeyPair != null) {
        return jwtBuilderFactory.jwe(encryptionKeyPair.getPublic()).headers().alg(JweAlgorithm.RSAES_PKCS1_V1_5).enc(EncryptionMethod.A128CBC_HS256).done().claims(claimsSet).sign(signingHandler, jwsAlgorithm).build();
    } else {
        return jwtBuilderFactory.jws(signingHandler).headers().alg(jwsAlgorithm).done().claims(claimsSet).build();
    }
}
Also used : JwtClaimsSet(org.forgerock.json.jose.jwt.JwtClaimsSet)

Example 7 with JwtClaimsSet

use of org.forgerock.json.jose.jwt.JwtClaimsSet in project OpenAM by OpenRock.

the class OpenIdConnectToken method sign.

/**
     * Signs the OpenId Connect token.
     *
     * @return A SignedJwt
     * @throws SignatureException If an error occurs with the signing of the OpenId Connect token.
     */
public SignedJwt sign() throws SignatureException {
    final JwsAlgorithm jwsAlgorithm = JwsAlgorithm.valueOf(algorithm);
    if (jwsAlgorithm == null) {
        logger.error("Unable to find jws algorithm for: " + algorithm);
        throw new SignatureException();
    }
    final SigningHandler signingHandler;
    if (JwsAlgorithmType.RSA.equals(jwsAlgorithm.getAlgorithmType())) {
        signingHandler = new SigningManager().newRsaSigningHandler(keyPair.getPrivate());
    } else {
        signingHandler = new SigningManager().newHmacSigningHandler(clientSecret);
    }
    JwsHeaderBuilder builder = jwtBuilderFactory.jws(signingHandler).headers().alg(jwsAlgorithm);
    JwtClaimsSet claimsSet = jwtBuilderFactory.claims().claims(asMap()).build();
    if (kid != null) {
        builder.kid(kid);
    }
    return builder.done().claims(claimsSet).asJwt();
}
Also used : JwsAlgorithm(org.forgerock.json.jose.jws.JwsAlgorithm) JwtClaimsSet(org.forgerock.json.jose.jwt.JwtClaimsSet) SignatureException(java.security.SignatureException) JwsHeaderBuilder(org.forgerock.json.jose.builders.JwsHeaderBuilder) SigningHandler(org.forgerock.json.jose.jws.handlers.SigningHandler) SigningManager(org.forgerock.json.jose.jws.SigningManager)

Example 8 with JwtClaimsSet

use of org.forgerock.json.jose.jwt.JwtClaimsSet in project OpenAM by OpenRock.

the class OpenIDConnectEndSession method endSession.

/**
     * Ends an OpenId Connect session.
     *
     * @param idToken The OpenId Token.
     * @throws BadRequestException If the request is malformed.
     * @throws ServerException If any internal server error occurs.
     */
public void endSession(String idToken) throws BadRequestException, ServerException {
    if (idToken == null || idToken.isEmpty()) {
        logger.warn("No id_token_hint parameter supplied to the endSession endpoint");
        throw new BadRequestException("The endSession endpoint requires an id_token_hint parameter");
    }
    JwtReconstruction jwtReconstruction = new JwtReconstruction();
    SignedJwt jwt = jwtReconstruction.reconstructJwt(idToken, SignedJwt.class);
    JwtClaimsSet claims = jwt.getClaimsSet();
    String opsId = (String) claims.getClaim(OAuth2Constants.JWTTokenParams.OPS);
    if (opsId == null) {
        opsId = (String) claims.getClaim(OAuth2Constants.JWTTokenParams.LEGACY_OPS);
    }
    openIDConnectProvider.destroySession(opsId);
}
Also used : JwtClaimsSet(org.forgerock.json.jose.jwt.JwtClaimsSet) JwtReconstruction(org.forgerock.json.jose.common.JwtReconstruction) BadRequestException(org.forgerock.oauth2.core.exceptions.BadRequestException) SignedJwt(org.forgerock.json.jose.jws.SignedJwt)

Example 9 with JwtClaimsSet

use of org.forgerock.json.jose.jwt.JwtClaimsSet in project OpenAM by OpenRock.

the class OpenIdConnectTokenGenerationImplTest method testRSAOpenIdConnectTokenGeneration.

@Test
public void testRSAOpenIdConnectTokenGeneration() throws TokenCreationException {
    SSOTokenIdentity mockSSOTokenIdentity = mock(SSOTokenIdentity.class);
    when(mockSSOTokenIdentity.validateAndGetTokenPrincipal(any(SSOToken.class))).thenReturn(SUBJECT_NAME);
    SSOToken mockSSOToken = mock(SSOToken.class);
    STSInstanceState mockSTSInstanceState = mock(STSInstanceState.class);
    STSInstanceConfig mockSTSInstanceConfig = mock(STSInstanceConfig.class);
    when(mockSTSInstanceState.getConfig()).thenReturn(mockSTSInstanceConfig);
    OpenIdConnectTokenConfig openIdConnectTokenConfig = buildRSAOpenIdConnectTokenConfig();
    when(mockSTSInstanceConfig.getOpenIdConnectTokenConfig()).thenReturn(openIdConnectTokenConfig);
    OpenIdConnectTokenPKIProviderImpl tokenCryptoProvider = new OpenIdConnectTokenPKIProviderImpl(openIdConnectTokenConfig);
    when(mockSTSInstanceState.getOpenIdConnectTokenPKIProvider()).thenReturn(tokenCryptoProvider);
    TokenGenerationServiceInvocationState mockTokenGenerationInvocationState = mock(TokenGenerationServiceInvocationState.class);
    OpenIdConnectTokenClaimMapperProvider mockClaimMapperProvider = mock(OpenIdConnectTokenClaimMapperProvider.class);
    OpenIdConnectTokenClaimMapper mockClaimMapper = mock(OpenIdConnectTokenClaimMapper.class);
    when(mockClaimMapperProvider.getClaimMapper(any(OpenIdConnectTokenConfig.class))).thenReturn(mockClaimMapper);
    when(mockClaimMapper.getCustomClaims(mockSSOToken, mappedClaimConfig)).thenReturn(mappedClaimAttributes);
    long authTime = System.currentTimeMillis() / 1000;
    OpenIdConnectTokenGenerationState openIdConnectTokenGenerationState = buildOpenIdConnectTokenGenerationState(authTime);
    when(mockTokenGenerationInvocationState.getOpenIdConnectTokenGenerationState()).thenReturn(openIdConnectTokenGenerationState);
    String oidcToken = new OpenIdConnectTokenGenerationImpl(mockSSOTokenIdentity, new JwtBuilderFactory(), mockClaimMapperProvider, mock(CTSTokenPersistence.class), mock(Logger.class)).generate(mockSSOToken, mockSTSInstanceState, mockTokenGenerationInvocationState);
    SignedJwt signedJwt = reconstructSignedJwt(oidcToken);
    JwtClaimsSet jwtClaimsSet = signedJwt.getClaimsSet();
    assertEquals(SUBJECT_NAME, jwtClaimsSet.getSubject());
    assertEquals(AUDIENCE, jwtClaimsSet.getAudience().get(0));
    assertEquals(AUTHN_CLASS_REFERENCE, jwtClaimsSet.getClaim("acr", String.class));
    assertEquals(ISSUER, jwtClaimsSet.getIssuer());
    assertEquals(EMAIL_CLAIM_VALUE, jwtClaimsSet.get(EMAIL_CLAIM_KEY).asString());
    assertTrue(verifyRSASignature(signedJwt, openIdConnectTokenConfig));
}
Also used : JwtBuilderFactory(org.forgerock.json.jose.builders.JwtBuilderFactory) SSOToken(com.iplanet.sso.SSOToken) STSInstanceState(org.forgerock.openam.sts.tokengeneration.state.STSInstanceState) SignedJwt(org.forgerock.json.jose.jws.SignedJwt) OpenIdConnectTokenConfig(org.forgerock.openam.sts.config.user.OpenIdConnectTokenConfig) TokenGenerationServiceInvocationState(org.forgerock.openam.sts.service.invocation.TokenGenerationServiceInvocationState) JwtClaimsSet(org.forgerock.json.jose.jwt.JwtClaimsSet) SSOTokenIdentity(org.forgerock.openam.sts.tokengeneration.SSOTokenIdentity) OpenIdConnectTokenPKIProviderImpl(org.forgerock.openam.sts.tokengeneration.oidc.crypto.OpenIdConnectTokenPKIProviderImpl) OpenIdConnectTokenGenerationState(org.forgerock.openam.sts.service.invocation.OpenIdConnectTokenGenerationState) STSInstanceConfig(org.forgerock.openam.sts.config.user.STSInstanceConfig) Test(org.testng.annotations.Test)

Example 10 with JwtClaimsSet

use of org.forgerock.json.jose.jwt.JwtClaimsSet in project OpenAM by OpenRock.

the class JwtGenerator method main.

public static void main(String[] args) throws Exception {
    if (args.length != 3) {
        System.out.println("Usage: JwtGenerator <subject> <issuer> <audience>");
        System.exit(1);
    }
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(512);
    KeyPair keyPair = keyGen.genKeyPair();
    PublicKey publicKey = keyPair.getPublic();
    long validTime = System.currentTimeMillis() + 1000 * 60 * 60 * 24 / 2;
    String jwt = new JwtBuilderFactory().jws(new SigningManager().newRsaSigningHandler(keyPair.getPrivate())).headers().alg(JwsAlgorithm.RS256).done().claims(new JwtClaimsSet(json(object(field("iss", args[0]), field("sub", args[1]), field("aud", args[2]), field("exp", validTime / 1000))).asMap())).build();
    System.out.println("JWT: " + jwt);
    Calendar expiry = Calendar.getInstance();
    expiry.add(Calendar.DAY_OF_YEAR, 7);
    X509CertInfo info = new X509CertInfo();
    CertificateValidity interval = new CertificateValidity(new Date(), new Date(validTime));
    BigInteger sn = new BigInteger(64, new SecureRandom());
    X500Name owner = new X500Name("CN=ForgeRock,L=Bristol,C=GB");
    info.set(X509CertInfo.VALIDITY, interval);
    info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
    info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner));
    info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner));
    info.set(X509CertInfo.KEY, new CertificateX509Key(publicKey));
    info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
    AlgorithmId algo = new AlgorithmId(AlgorithmId.sha256WithRSAEncryption_oid);
    info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo));
    // Sign the cert to identify the algorithm that's used.
    X509CertImpl cert = new X509CertImpl(info);
    cert.sign(keyPair.getPrivate(), "SHA256withRSA");
    System.out.println("Certificate:");
    BASE64Encoder encoder = new BASE64Encoder();
    System.out.println(X509Factory.BEGIN_CERT);
    encoder.encodeBuffer(cert.getEncoded(), System.out);
    System.out.println(X509Factory.END_CERT);
}
Also used : JwtBuilderFactory(org.forgerock.json.jose.builders.JwtBuilderFactory) CertificateSubjectName(sun.security.x509.CertificateSubjectName) KeyPair(java.security.KeyPair) X509CertInfo(sun.security.x509.X509CertInfo) PublicKey(java.security.PublicKey) Calendar(java.util.Calendar) CertificateIssuerName(sun.security.x509.CertificateIssuerName) BASE64Encoder(sun.misc.BASE64Encoder) SecureRandom(java.security.SecureRandom) CertificateVersion(sun.security.x509.CertificateVersion) CertificateValidity(sun.security.x509.CertificateValidity) KeyPairGenerator(java.security.KeyPairGenerator) X500Name(sun.security.x509.X500Name) CertificateX509Key(sun.security.x509.CertificateX509Key) SigningManager(org.forgerock.json.jose.jws.SigningManager) Date(java.util.Date) CertificateSerialNumber(sun.security.x509.CertificateSerialNumber) JwtClaimsSet(org.forgerock.json.jose.jwt.JwtClaimsSet) CertificateAlgorithmId(sun.security.x509.CertificateAlgorithmId) AlgorithmId(sun.security.x509.AlgorithmId) X509CertImpl(sun.security.x509.X509CertImpl) BigInteger(java.math.BigInteger) CertificateAlgorithmId(sun.security.x509.CertificateAlgorithmId)

Aggregations

JwtClaimsSet (org.forgerock.json.jose.jwt.JwtClaimsSet)35 Test (org.testng.annotations.Test)16 SigningHandler (org.forgerock.json.jose.jws.handlers.SigningHandler)11 SignedJwt (org.forgerock.json.jose.jws.SignedJwt)8 AuthLoginException (com.sun.identity.authentication.spi.AuthLoginException)7 Callback (javax.security.auth.callback.Callback)7 HttpServletRequest (javax.servlet.http.HttpServletRequest)7 JwsHeader (org.forgerock.json.jose.jws.JwsHeader)7 NOPSigningHandler (org.forgerock.json.jose.jws.handlers.NOPSigningHandler)7 Jwt (org.forgerock.json.jose.jwt.Jwt)7 HashMap (java.util.HashMap)6 Map (java.util.Map)5 SigningManager (org.forgerock.json.jose.jws.SigningManager)5 Set (java.util.Set)4 Subject (javax.security.auth.Subject)4 MessageInfo (javax.security.auth.message.MessageInfo)4 JwsHeaderBuilder (org.forgerock.json.jose.builders.JwsHeaderBuilder)4 JwtBuilderFactory (org.forgerock.json.jose.builders.JwtBuilderFactory)4 SSOToken (com.iplanet.sso.SSOToken)3 SSOException (com.iplanet.sso.SSOException)2