Search in sources :

Example 76 with RSASigner

use of io.jans.as.model.jws.RSASigner in project jans by JanssenProject.

the class MultivaluedClaims method authorizationRequestObjectWithMultivaluedClaimRS256.

@Parameters({ "userId", "userSecret", "redirectUri", "redirectUris", "dnName", "keyStoreFile", "keyStoreSecret", "sectorIdentifierUri", "RS256_keyId", "clientJwksUri" })
@Test
public void authorizationRequestObjectWithMultivaluedClaimRS256(final String userId, final String userSecret, final String redirectUri, final String redirectUris, final String dnName, final String keyStoreFile, final String keyStoreSecret, final String sectorIdentifierUri, final String keyId, final String clientJwksUri) throws Exception {
    showTitle("authorizationRequestObjectWithMultivaluedClaimRS256");
    List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN, ResponseType.ID_TOKEN);
    // 1. Register client
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "jans test app", StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setResponseTypes(responseTypes);
    registerRequest.setSectorIdentifierUri(sectorIdentifierUri);
    registerRequest.setIdTokenSignedResponseAlg(SignatureAlgorithm.RS256);
    registerRequest.setUserInfoSignedResponseAlg(SignatureAlgorithm.RS256);
    registerRequest.setRequestObjectSigningAlg(SignatureAlgorithm.RS256);
    registerRequest.setJwksUri(clientJwksUri);
    registerRequest.setClaims(Arrays.asList("member_of"));
    RegisterClient registerClient = new RegisterClient(registrationEndpoint);
    registerClient.setRequest(registerRequest);
    RegisterResponse registerResponse = registerClient.exec();
    showClient(registerClient);
    assertRegisterResponseOk(registerResponse, 201, true);
    String clientId = registerResponse.getClientId();
    // 2. Request authorization
    AuthCryptoProvider cryptoProvider = new AuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);
    List<String> scopes = Arrays.asList("openid");
    String nonce = UUID.randomUUID().toString();
    String state = UUID.randomUUID().toString();
    AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce);
    authorizationRequest.setState(state);
    JwtAuthorizationRequest jwtAuthorizationRequest = new JwtAuthorizationRequest(authorizationRequest, SignatureAlgorithm.RS256, cryptoProvider);
    jwtAuthorizationRequest.setKeyId(keyId);
    jwtAuthorizationRequest.addIdTokenClaim(new Claim(JwtClaimName.AUTHENTICATION_TIME, ClaimValue.createEssential(true)));
    jwtAuthorizationRequest.addIdTokenClaim(new Claim("member_of", ClaimValue.createEssential(true)));
    jwtAuthorizationRequest.addUserInfoClaim(new Claim("member_of", ClaimValue.createEssential(true)));
    String authJwt = jwtAuthorizationRequest.getEncodedJwt();
    authorizationRequest.setRequest(authJwt);
    AuthorizeClient authorizeClient = new AuthorizeClient(authorizationEndpoint);
    authorizeClient.setRequest(authorizationRequest);
    AuthorizationResponse authorizationResponse = authenticateResourceOwnerAndGrantAccess(authorizationEndpoint, authorizationRequest, userId, userSecret);
    assertAuthorizationResponse(authorizationResponse, responseTypes, true);
    String idToken = authorizationResponse.getIdToken();
    String accessToken = authorizationResponse.getAccessToken();
    // 3. Validate id_token
    Jwt jwt = Jwt.parse(idToken);
    assertJwtStandarClaimsNotNull(jwt, true);
    assertNotNull(jwt.getClaims().getClaimAsStringList("member_of"));
    assertTrue(jwt.getClaims().getClaimAsStringList("member_of").size() > 1);
    RSAPublicKey publicKey = JwkClient.getRSAPublicKey(jwksUri, jwt.getHeader().getClaimAsString(JwtHeaderName.KEY_ID));
    RSASigner rsaSigner = new RSASigner(SignatureAlgorithm.RS256, publicKey);
    assertTrue(rsaSigner.validate(jwt));
    // 4. Request user info
    UserInfoRequest userInfoRequest = new UserInfoRequest(accessToken);
    UserInfoClient userInfoClient = new UserInfoClient(userInfoEndpoint);
    userInfoClient.setRequest(userInfoRequest);
    userInfoClient.setJwksUri(jwksUri);
    UserInfoResponse userInfoResponse = userInfoClient.exec();
    showClient(userInfoClient);
    assertEquals(userInfoResponse.getStatus(), 200, "Unexpected response code: " + userInfoResponse.getStatus());
    assertNotNull(userInfoResponse.getClaim(JwtClaimName.SUBJECT_IDENTIFIER));
    assertNotNull(userInfoResponse.getClaim("member_of"));
    assertTrue(userInfoResponse.getClaim("member_of").size() > 1);
}
Also used : RegisterRequest(io.jans.as.client.RegisterRequest) AuthorizationRequest(io.jans.as.client.AuthorizationRequest) JwtAuthorizationRequest(io.jans.as.client.model.authorize.JwtAuthorizationRequest) Jwt(io.jans.as.model.jwt.Jwt) UserInfoRequest(io.jans.as.client.UserInfoRequest) UserInfoClient(io.jans.as.client.UserInfoClient) ResponseType(io.jans.as.model.common.ResponseType) AuthorizationResponse(io.jans.as.client.AuthorizationResponse) RegisterResponse(io.jans.as.client.RegisterResponse) RSAPublicKey(io.jans.as.model.crypto.signature.RSAPublicKey) RegisterClient(io.jans.as.client.RegisterClient) RSASigner(io.jans.as.model.jws.RSASigner) JwtAuthorizationRequest(io.jans.as.client.model.authorize.JwtAuthorizationRequest) UserInfoResponse(io.jans.as.client.UserInfoResponse) AuthorizeClient(io.jans.as.client.AuthorizeClient) AuthCryptoProvider(io.jans.as.model.crypto.AuthCryptoProvider) Claim(io.jans.as.client.model.authorize.Claim) Parameters(org.testng.annotations.Parameters) Test(org.testng.annotations.Test) BaseTest(io.jans.as.client.BaseTest)

Example 77 with RSASigner

use of io.jans.as.model.jws.RSASigner in project jans by JanssenProject.

the class ResponseTypesRestrictionHttpTest method responseTypesCodeIdToken.

/**
 * Registering with the response_types param <code>code, id_token</code>.
 */
@Parameters({ "redirectUris", "userId", "userSecret", "redirectUri", "sectorIdentifierUri" })
@Test
public void responseTypesCodeIdToken(final String redirectUris, final String userId, final String userSecret, final String redirectUri, final String sectorIdentifierUri) throws Exception {
    showTitle("responseTypesCodeIdToken");
    List<ResponseType> responseTypes = Arrays.asList(ResponseType.CODE, ResponseType.ID_TOKEN);
    // 1. Register client
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "jans test app", StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setResponseTypes(responseTypes);
    registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.CLIENT_SECRET_POST);
    registerRequest.setSectorIdentifierUri(sectorIdentifierUri);
    RegisterClient registerClient = new RegisterClient(registrationEndpoint);
    registerClient.setRequest(registerRequest);
    RegisterResponse registerResponse = registerClient.exec();
    showClient(registerClient);
    assertRegisterResponseOk(registerResponse, 201, true);
    String clientId = registerResponse.getClientId();
    String clientSecret = registerResponse.getClientSecret();
    String registrationAccessToken = registerResponse.getRegistrationAccessToken();
    String registrationClientUri = registerResponse.getRegistrationClientUri();
    // 2. Client read
    RegisterRequest readClientRequest = new RegisterRequest(registrationAccessToken);
    RegisterClient readClient = new RegisterClient(registrationClientUri);
    readClient.setRequest(readClientRequest);
    RegisterResponse readClientResponse = readClient.exec();
    showClient(readClient);
    assertRegisterResponseOk(readClientResponse, 200, false);
    assertRegisterResponseClaimsNotNull(readClientResponse, RESPONSE_TYPES, REDIRECT_URIS.APPLICATION_TYPE, CLIENT_NAME, ID_TOKEN_SIGNED_RESPONSE_ALG, SCOPE);
    // 3. Request authorization
    List<String> scopes = Arrays.asList("openid", "profile", "address", "email");
    String state = UUID.randomUUID().toString();
    String nonce = UUID.randomUUID().toString();
    AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce);
    authorizationRequest.setState(state);
    AuthorizationResponse authorizationResponse = authenticateResourceOwnerAndGrantAccess(authorizationEndpoint, authorizationRequest, userId, userSecret);
    assertAuthorizationResponse(authorizationResponse, responseTypes, true);
    String authorizationCode = authorizationResponse.getCode();
    String idToken = authorizationResponse.getIdToken();
    // 4. Validate code and id_token
    Jwt jwt = Jwt.parse(idToken);
    assertJwtStandarClaimsNotNull(jwt, false);
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.CODE_HASH));
    RSAPublicKey publicKey = JwkClient.getRSAPublicKey(jwksUri, jwt.getHeader().getClaimAsString(JwtHeaderName.KEY_ID));
    RSASigner rsaSigner = new RSASigner(SignatureAlgorithm.RS256, publicKey);
    assertTrue(rsaSigner.validate(jwt));
    assertTrue(rsaSigner.validateAuthorizationCode(authorizationCode, jwt));
    // 5. Get Access Token
    TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest.setCode(authorizationCode);
    tokenRequest.setRedirectUri(redirectUri);
    tokenRequest.setAuthUsername(clientId);
    tokenRequest.setAuthPassword(clientSecret);
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_POST);
    TokenClient tokenClient = new TokenClient(tokenEndpoint);
    tokenClient.setRequest(tokenRequest);
    TokenResponse tokenResponse1 = tokenClient.exec();
    showClient(tokenClient);
    assertTokenResponseOk(tokenResponse1, true);
}
Also used : RegisterRequest(io.jans.as.client.RegisterRequest) AuthorizationRequest(io.jans.as.client.AuthorizationRequest) Jwt(io.jans.as.model.jwt.Jwt) ResponseType(io.jans.as.model.common.ResponseType) AuthorizationResponse(io.jans.as.client.AuthorizationResponse) RegisterResponse(io.jans.as.client.RegisterResponse) RSAPublicKey(io.jans.as.model.crypto.signature.RSAPublicKey) TokenResponse(io.jans.as.client.TokenResponse) RegisterClient(io.jans.as.client.RegisterClient) RSASigner(io.jans.as.model.jws.RSASigner) TokenRequest(io.jans.as.client.TokenRequest) TokenClient(io.jans.as.client.TokenClient) Parameters(org.testng.annotations.Parameters) Test(org.testng.annotations.Test) BaseTest(io.jans.as.client.BaseTest)

Example 78 with RSASigner

use of io.jans.as.model.jws.RSASigner in project jans by JanssenProject.

the class UmaValidationService method isIdTokenValid.

public boolean isIdTokenValid(Jwt idToken) {
    try {
        final String issuer = idToken.getClaims().getClaimAsString(JwtClaimName.ISSUER);
        final Date expiresAt = idToken.getClaims().getClaimAsDate(JwtClaimName.EXPIRATION_TIME);
        final Date now = new Date();
        if (now.after(expiresAt)) {
            log.error("ID Token is expired. (It is after {}).", now);
            return false;
        }
        // 1. validate issuer
        if (!issuer.equals(appConfiguration.getIssuer())) {
            log.error("ID Token issuer is invalid. Token issuer: {}, server issuer: {}", issuer, appConfiguration.getIssuer());
            return false;
        }
        // 2. validate signature
        final String kid = idToken.getHeader().getClaimAsString(JwtHeaderName.KEY_ID);
        final String algorithm = idToken.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM);
        RSAPublicKey publicKey = getPublicKey(kid);
        if (publicKey != null) {
            RSASigner rsaSigner = new RSASigner(SignatureAlgorithm.fromString(algorithm), publicKey);
            boolean signature = rsaSigner.validate(idToken);
            if (signature) {
                log.debug("ID Token is successfully validated.");
                return true;
            }
            log.error("ID Token signature is invalid.");
        } else {
            log.error("Failed to get RSA public key.");
        }
        return false;
    } catch (Exception e) {
        log.error("Failed to validate id_token. Message: " + e.getMessage(), e);
        return false;
    }
}
Also used : RSAPublicKey(io.jans.as.model.crypto.signature.RSAPublicKey) RSASigner(io.jans.as.model.jws.RSASigner) Date(java.util.Date) UmaWebException(io.jans.as.server.uma.authorization.UmaWebException) EntryPersistenceException(io.jans.orm.exception.EntryPersistenceException)

Example 79 with RSASigner

use of io.jans.as.model.jws.RSASigner in project jans by JanssenProject.

the class CheckAccessTokenOperation method isAccessTokenValid.

private boolean isAccessTokenValid(String p_accessToken, Jwt jwt, OpenIdConfigurationResponse discoveryResponse) {
    try {
        // final String type = jwt.getHeader().getClaimAsString(JwtHeaderName.TYPE);
        final String algorithm = jwt.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM);
        final String jwkUrl = discoveryResponse.getJwksUri();
        final String kid = jwt.getHeader().getClaimAsString(JwtHeaderName.KEY_ID);
        final SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.fromString(algorithm);
        final RSAPublicKey publicKey = JwkClient.getRSAPublicKey(jwkUrl, kid);
        final RSASigner rsaSigner = new RSASigner(signatureAlgorithm, publicKey);
        return rsaSigner.validateAccessToken(p_accessToken, jwt);
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        return false;
    }
}
Also used : RSAPublicKey(io.jans.as.model.crypto.signature.RSAPublicKey) RSASigner(io.jans.as.model.jws.RSASigner) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm)

Example 80 with RSASigner

use of io.jans.as.model.jws.RSASigner in project jans by JanssenProject.

the class JwtUtil method validateSignature.

public boolean validateSignature(Jwt jwt, JSONWebKeySet jsonWebKeySet) {
    log.trace("\n\n JwtUtil::validateSignature() - jwt = " + jwt + " , jsonWebKeySet =" + jsonWebKeySet + "\n");
    try {
        final String kid = jwt.getHeader().getClaimAsString(JwtHeaderName.KEY_ID);
        final String algorithm = jwt.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM);
        final SignatureAlgorithm signatureAlgorithm = jwt.getHeader().getSignatureAlgorithm();
        log.trace("\n\n JwtUtil::validateSignature() - kid = " + kid + " , algorithm =" + algorithm + " signatureAlgorithm = " + signatureAlgorithm + "\n");
        PublicKey publicKey = getPublicKey(kid, jsonWebKeySet, signatureAlgorithm);
        log.trace("\n\n JwtUtil::validateSignature() - publicKey = " + publicKey + "\n");
        if (publicKey == null) {
            log.error("Failed to get RSA public key.");
            return false;
        }
        // Validate
        AbstractJwsSigner signer = null;
        if (AlgorithmFamily.RSA.equals(signatureAlgorithm.getFamily())) {
            signer = new RSASigner(SignatureAlgorithm.fromString(algorithm), (RSAPublicKey) publicKey);
        } else if (AlgorithmFamily.EC.equals(signatureAlgorithm.getFamily())) {
            signer = new ECDSASigner(SignatureAlgorithm.fromString(algorithm), (ECDSAPublicKey) publicKey);
        }
        if (signer == null) {
            log.error("ID Token signer is not found!");
            return false;
        }
        boolean signature = signer.validate(jwt);
        if (signature) {
            log.debug("ID Token is successfully validated.");
            return true;
        }
        log.error("ID Token signature invalid.");
        return false;
    } catch (Exception e) {
        log.error("Failed to validate id_token. Message: " + e.getMessage(), e);
        return false;
    }
}
Also used : RSAPublicKey(io.jans.as.model.crypto.signature.RSAPublicKey) ECDSASigner(io.jans.as.model.jws.ECDSASigner) ECDSAPublicKey(io.jans.as.model.crypto.signature.ECDSAPublicKey) PublicKey(io.jans.as.model.crypto.PublicKey) RSAPublicKey(io.jans.as.model.crypto.signature.RSAPublicKey) RSASigner(io.jans.as.model.jws.RSASigner) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) AbstractJwsSigner(io.jans.as.model.jws.AbstractJwsSigner) InvalidJwtException(io.jans.as.model.exception.InvalidJwtException) IOException(java.io.IOException) WebApplicationException(javax.ws.rs.WebApplicationException)

Aggregations

RSASigner (io.jans.as.model.jws.RSASigner)107 RSAPublicKey (io.jans.as.model.crypto.signature.RSAPublicKey)106 Jwt (io.jans.as.model.jwt.Jwt)100 Test (org.testng.annotations.Test)94 AuthorizationResponse (io.jans.as.client.AuthorizationResponse)92 BaseTest (io.jans.as.client.BaseTest)90 RegisterResponse (io.jans.as.client.RegisterResponse)90 ResponseType (io.jans.as.model.common.ResponseType)90 Parameters (org.testng.annotations.Parameters)89 AuthorizationRequest (io.jans.as.client.AuthorizationRequest)86 RegisterClient (io.jans.as.client.RegisterClient)83 RegisterRequest (io.jans.as.client.RegisterRequest)83 AuthorizeClient (io.jans.as.client.AuthorizeClient)53 UserInfoClient (io.jans.as.client.UserInfoClient)49 UserInfoResponse (io.jans.as.client.UserInfoResponse)49 JwtAuthorizationRequest (io.jans.as.client.model.authorize.JwtAuthorizationRequest)40 AuthCryptoProvider (io.jans.as.model.crypto.AuthCryptoProvider)25 TokenClient (io.jans.as.client.TokenClient)24 TokenResponse (io.jans.as.client.TokenResponse)24 Claim (io.jans.as.client.model.authorize.Claim)24