Search in sources :

Example 1 with AuthenticationMethod

use of io.jans.as.model.common.AuthenticationMethod in project jans by JanssenProject.

the class RegisterSiteOperation method createRegisterClientRequest.

private RegisterRequest createRegisterClientRequest(RegisterSiteParams params, String rpId) {
    String clientName = "jans_client_api client for rp: " + rpId;
    if (!Strings.isNullOrEmpty(params.getClientName())) {
        clientName = params.getClientName();
    }
    final RegisterRequest request = new RegisterRequest(ApplicationType.WEB, clientName, params.getRedirectUris());
    request.setResponseTypesStrings(params.getResponseTypes());
    request.setJwksUri(params.getClientJwksUri());
    request.setClaimsRedirectUris(params.getClaimsRedirectUri() != null ? params.getClaimsRedirectUri() : new ArrayList<String>());
    request.setPostLogoutRedirectUris(params.getPostLogoutRedirectUris() != null ? params.getPostLogoutRedirectUris() : Lists.newArrayList());
    request.setContacts(params.getContacts());
    request.setScope(params.getScope());
    request.setDefaultAcrValues(params.getAcrValues());
    if (StringUtils.isNotBlank(params.getClientTokenEndpointAuthSigningAlg())) {
        SignatureAlgorithm signatureAlgorithms = SignatureAlgorithm.fromString(params.getClientTokenEndpointAuthSigningAlg());
        if (signatureAlgorithms == null) {
            LOG.error("Received invalid algorithm in `client_token_endpoint_auth_signing_alg` property. Value: " + params.getClientTokenEndpointAuthSigningAlg());
            throw new HttpException(ErrorResponseCode.INVALID_SIGNATURE_ALGORITHM);
        }
        request.setTokenEndpointAuthSigningAlg(signatureAlgorithms);
    }
    if (StringUtils.isNotBlank(rpId)) {
        request.addCustomAttribute("rp_id", rpId);
    }
    List<GrantType> grantTypes = Lists.newArrayList();
    for (String grantType : params.getGrantTypes()) {
        grantTypes.add(GrantType.fromString(grantType));
    }
    request.setGrantTypes(grantTypes);
    if (StringUtils.isNotBlank(params.getClientFrontchannelLogoutUri())) {
        request.setFrontChannelLogoutUri(params.getClientFrontchannelLogoutUri());
    }
    if (StringUtils.isNotBlank(params.getClientTokenEndpointAuthMethod())) {
        final AuthenticationMethod authenticationMethod = AuthenticationMethod.fromString(params.getClientTokenEndpointAuthMethod());
        if (authenticationMethod != null) {
            request.setTokenEndpointAuthMethod(authenticationMethod);
        }
    }
    if (params.getClientRequestUris() != null && !params.getClientRequestUris().isEmpty()) {
        request.setRequestUris(params.getClientRequestUris());
    }
    if (!Strings.isNullOrEmpty(params.getClientSectorIdentifierUri())) {
        request.setSectorIdentifierUri(params.getClientSectorIdentifierUri());
    }
    request.setAccessTokenAsJwt(params.getAccessTokenAsJwt());
    request.setAccessTokenSigningAlg(SignatureAlgorithm.fromString(params.getAccessTokenSigningAlg()));
    request.setRptAsJwt(params.getRptAsJwt());
    if (!Strings.isNullOrEmpty(params.getLogoUri())) {
        request.setLogoUri(params.getLogoUri());
    }
    if (!Strings.isNullOrEmpty(params.getClientUri())) {
        request.setClientUri(params.getClientUri());
    }
    if (!Strings.isNullOrEmpty(params.getPolicyUri())) {
        request.setPolicyUri(params.getPolicyUri());
    }
    if (params.getFrontChannelLogoutSessionRequired() != null) {
        request.setFrontChannelLogoutSessionRequired(params.getFrontChannelLogoutSessionRequired());
    }
    if (!Strings.isNullOrEmpty(params.getTosUri())) {
        request.setTosUri(params.getTosUri());
    }
    if (!Strings.isNullOrEmpty(params.getJwks())) {
        request.setJwks(params.getJwks());
    }
    if (!Strings.isNullOrEmpty(params.getIdTokenBindingCnf())) {
        request.setIdTokenTokenBindingCnf(params.getIdTokenBindingCnf());
    }
    if (!Strings.isNullOrEmpty(params.getTlsClientAuthSubjectDn())) {
        request.setTlsClientAuthSubjectDn(params.getTlsClientAuthSubjectDn());
    }
    if (!Strings.isNullOrEmpty(params.getSubjectType())) {
        SubjectType subjectType = SubjectType.fromString(params.getSubjectType());
        if (subjectType == null) {
            LOG.error("Received invalid values in `subject_type` property. Value: " + params.getSubjectType());
            throw new HttpException(ErrorResponseCode.INVALID_SUBJECT_TYPE);
        }
        request.setSubjectType(subjectType);
    }
    if (params.getRunIntrospectionScriptBeforeAccessTokenAsJwtCreationAndIncludeClaims() != null) {
        request.setRunIntrospectionScriptBeforeAccessTokenAsJwtCreationAndIncludeClaims(params.getRunIntrospectionScriptBeforeAccessTokenAsJwtCreationAndIncludeClaims());
    }
    if (!Strings.isNullOrEmpty(params.getIdTokenSignedResponseAlg())) {
        SignatureAlgorithm signatureAlgorithms = SignatureAlgorithm.fromString(params.getIdTokenSignedResponseAlg());
        if (signatureAlgorithms == null) {
            LOG.error("Received invalid algorithm in `id_token_signed_response_alg` property. Value: " + params.getIdTokenSignedResponseAlg());
            throw new HttpException(ErrorResponseCode.INVALID_SIGNATURE_ALGORITHM);
        }
        if (signatureAlgorithms == SignatureAlgorithm.NONE && !getConfigurationService().getConfiguration().getAcceptIdTokenWithoutSignature()) {
            LOG.error("`ID_TOKEN` without signature is not allowed. To allow `ID_TOKEN` without signature set `accept_id_token_without_signature` field to 'true' in client-api-server.yml.");
            throw new HttpException(ErrorResponseCode.ID_TOKEN_WITHOUT_SIGNATURE_NOT_ALLOWED);
        }
        request.setIdTokenSignedResponseAlg(signatureAlgorithms);
    }
    if (!Strings.isNullOrEmpty(params.getIdTokenEncryptedResponseAlg())) {
        KeyEncryptionAlgorithm keyEncryptionAlgorithms = KeyEncryptionAlgorithm.fromName(params.getIdTokenEncryptedResponseAlg());
        if (keyEncryptionAlgorithms == null) {
            LOG.error("Received invalid algorithm in `id_token_encrypted_response_alg` property. Value: " + params.getIdTokenEncryptedResponseAlg());
            throw new HttpException(ErrorResponseCode.INVALID_KEY_ENCRYPTION_ALGORITHM);
        }
        request.setIdTokenEncryptedResponseAlg(keyEncryptionAlgorithms);
    }
    if (!Strings.isNullOrEmpty(params.getIdTokenEncryptedResponseEnc())) {
        BlockEncryptionAlgorithm blockEncryptionAlgorithms = BlockEncryptionAlgorithm.fromName(params.getIdTokenEncryptedResponseEnc());
        if (blockEncryptionAlgorithms == null) {
            LOG.error("Received invalid algorithm in `id_token_encrypted_response_enc` property. Value: " + params.getIdTokenEncryptedResponseEnc());
            throw new HttpException(ErrorResponseCode.INVALID_BLOCK_ENCRYPTION_ALGORITHM);
        }
        request.setIdTokenEncryptedResponseEnc(blockEncryptionAlgorithms);
    }
    if (!Strings.isNullOrEmpty(params.getUserInfoSignedResponseAlg())) {
        SignatureAlgorithm signatureAlgorithms = SignatureAlgorithm.fromString(params.getUserInfoSignedResponseAlg());
        if (signatureAlgorithms == null) {
            LOG.error("Received invalid algorithm in `user_info_signed_response_alg` property. Value: " + params.getUserInfoSignedResponseAlg());
            throw new HttpException(ErrorResponseCode.INVALID_SIGNATURE_ALGORITHM);
        }
        request.setUserInfoSignedResponseAlg(signatureAlgorithms);
    }
    if (!Strings.isNullOrEmpty(params.getUserInfoEncryptedResponseAlg())) {
        KeyEncryptionAlgorithm keyEncryptionAlgorithms = KeyEncryptionAlgorithm.fromName(params.getUserInfoEncryptedResponseAlg());
        if (keyEncryptionAlgorithms == null) {
            LOG.error("Received invalid algorithm in `user_info_encrypted_response_alg` property. Value: " + params.getUserInfoEncryptedResponseAlg());
            throw new HttpException(ErrorResponseCode.INVALID_KEY_ENCRYPTION_ALGORITHM);
        }
        request.setUserInfoEncryptedResponseAlg(keyEncryptionAlgorithms);
    }
    if (!Strings.isNullOrEmpty(params.getUserInfoEncryptedResponseEnc())) {
        BlockEncryptionAlgorithm blockEncryptionAlgorithms = BlockEncryptionAlgorithm.fromName(params.getUserInfoEncryptedResponseEnc());
        if (blockEncryptionAlgorithms == null) {
            LOG.error("Received invalid algorithm in `user_info_encrypted_response_enc` property. Value: " + params.getUserInfoEncryptedResponseEnc());
            throw new HttpException(ErrorResponseCode.INVALID_BLOCK_ENCRYPTION_ALGORITHM);
        }
        request.setUserInfoEncryptedResponseEnc(blockEncryptionAlgorithms);
    }
    if (!Strings.isNullOrEmpty(params.getRequestObjectSigningAlg())) {
        SignatureAlgorithm signatureAlgorithms = SignatureAlgorithm.fromString(params.getRequestObjectSigningAlg());
        if (signatureAlgorithms == null) {
            LOG.error("Received invalid algorithm in `request_object_signing_alg` property. Value: " + params.getRequestObjectSigningAlg());
            throw new HttpException(ErrorResponseCode.INVALID_SIGNATURE_ALGORITHM);
        }
        request.setRequestObjectSigningAlg(signatureAlgorithms);
    }
    if (!Strings.isNullOrEmpty(params.getRequestObjectEncryptionAlg())) {
        KeyEncryptionAlgorithm keyEncryptionAlgorithms = KeyEncryptionAlgorithm.fromName(params.getRequestObjectEncryptionAlg());
        if (keyEncryptionAlgorithms == null) {
            LOG.error("Received invalid algorithm in `request_object_encryption_alg` property. Value: " + params.getRequestObjectEncryptionAlg());
            throw new HttpException(ErrorResponseCode.INVALID_KEY_ENCRYPTION_ALGORITHM);
        }
        request.setRequestObjectEncryptionAlg(keyEncryptionAlgorithms);
    }
    if (!Strings.isNullOrEmpty(params.getRequestObjectEncryptionEnc())) {
        BlockEncryptionAlgorithm blockEncryptionAlgorithms = BlockEncryptionAlgorithm.fromName(params.getRequestObjectEncryptionEnc());
        if (blockEncryptionAlgorithms == null) {
            LOG.error("Received invalid algorithm in `request_object_encryption_enc` property. Value: " + params.getRequestObjectEncryptionEnc());
            throw new HttpException(ErrorResponseCode.INVALID_BLOCK_ENCRYPTION_ALGORITHM);
        }
        request.setRequestObjectEncryptionEnc(blockEncryptionAlgorithms);
    }
    if (params.getDefaultMaxAge() != null && NumberUtils.isNumber(params.getDefaultMaxAge().toString())) {
        request.setDefaultMaxAge(params.getDefaultMaxAge());
    }
    if (params.getRequireAuthTime() != null) {
        request.setRequireAuthTime(params.getRequireAuthTime());
    }
    if (!Strings.isNullOrEmpty(params.getInitiateLoginUri())) {
        request.setInitiateLoginUri(params.getInitiateLoginUri());
    }
    if (params.getAuthorizedOrigins() != null && !params.getAuthorizedOrigins().isEmpty()) {
        request.setAuthorizedOrigins(params.getAuthorizedOrigins());
    }
    if (params.getAccessTokenLifetime() != null && NumberUtils.isNumber(params.getAccessTokenLifetime().toString())) {
        request.setAccessTokenLifetime(params.getAccessTokenLifetime());
    }
    if (!Strings.isNullOrEmpty(params.getSoftwareId())) {
        request.setSoftwareId(params.getSoftwareId());
    }
    if (!Strings.isNullOrEmpty(params.getSoftwareVersion())) {
        request.setSoftwareVersion(params.getSoftwareVersion());
    }
    if (!Strings.isNullOrEmpty(params.getSoftwareStatement())) {
        request.setSoftwareStatement(params.getSoftwareStatement());
    }
    if (params.getAllowSpontaneousScopes() != null) {
        request.setAllowSpontaneousScopes(params.getAllowSpontaneousScopes());
    }
    if (CollectionUtils.isNotEmpty(params.getSpontaneousScopes())) {
        request.setSpontaneousScopes(params.getSpontaneousScopes());
    }
    if (params.getCustomAttributes() != null && !params.getCustomAttributes().isEmpty()) {
        params.getCustomAttributes().entrySet().removeIf(entry -> entry.getKey().contains("oxAuthTrustedClient"));
        params.getCustomAttributes().entrySet().stream().forEach(e -> {
            request.addCustomAttribute(e.getKey(), e.getValue());
        });
    }
    return request;
}
Also used : RegisterRequest(io.jans.as.client.RegisterRequest) SubjectType(io.jans.as.model.common.SubjectType) KeyEncryptionAlgorithm(io.jans.as.model.crypto.encryption.KeyEncryptionAlgorithm) ArrayList(java.util.ArrayList) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) HttpException(io.jans.ca.server.HttpException) GrantType(io.jans.as.model.common.GrantType) AuthenticationMethod(io.jans.as.model.common.AuthenticationMethod) BlockEncryptionAlgorithm(io.jans.as.model.crypto.encryption.BlockEncryptionAlgorithm)

Example 2 with AuthenticationMethod

use of io.jans.as.model.common.AuthenticationMethod in project jans by JanssenProject.

the class GetTokensByCodeOperation method execute.

@Override
public IOpResponse execute(GetTokensByCodeParams params) throws Exception {
    validate(params);
    final Rp rp = getRp();
    OpenIdConfigurationResponse discoveryResponse = getDiscoveryService().getConnectDiscoveryResponse(rp);
    final TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest.setCode(params.getCode());
    tokenRequest.setRedirectUri(rp.getRedirectUri());
    tokenRequest.setAuthUsername(rp.getClientId());
    AuthenticationMethod authenticationMethod = Strings.isNullOrEmpty(params.getAuthenticationMethod()) ? AuthenticationMethod.fromString(rp.getTokenEndpointAuthMethod()) : AuthenticationMethod.fromString(params.getAuthenticationMethod());
    if (authenticationMethod == null) {
        LOG.debug("TokenEndpointAuthMethod is either not set or not valid. Setting `client_secret_basic` as AuthenticationMethod. TokenEndpointAuthMethod : {} ", rp.getTokenEndpointAuthMethod());
        tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);
    } else {
        tokenRequest.setAuthenticationMethod(authenticationMethod);
    }
    if (Lists.newArrayList(AuthenticationMethod.PRIVATE_KEY_JWT, AuthenticationMethod.TLS_CLIENT_AUTH, AuthenticationMethod.SELF_SIGNED_TLS_CLIENT_AUTH).contains(authenticationMethod)) {
        Algorithm algorithm = Strings.isNullOrEmpty(params.getAlgorithm()) ? Algorithm.fromString(rp.getTokenEndpointAuthSigningAlg()) : Algorithm.fromString(params.getAlgorithm());
        if (algorithm == null) {
            LOG.error("TokenEndpointAuthSigningAlg is either not set or not valid. TokenEndpointAuthSigningAlg : {} ", rp.getTokenEndpointAuthSigningAlg());
            throw new HttpException(ErrorResponseCode.INVALID_SIGNATURE_ALGORITHM);
        }
        tokenRequest.setAlgorithm(SignatureAlgorithm.fromString(rp.getTokenEndpointAuthSigningAlg()));
        if (!getConfigurationService().getConfiguration().getEnableJwksGeneration()) {
            LOG.error("The Token Authentication Method is {}. Please set `enable_jwks_generation` (to `true`), `crypt_provider_key_store_path` and `crypt_provider_key_store_password` in `client-api-server.yml` to enable RP-jwks generation in jans-client-api.", authenticationMethod.toString());
            throw new HttpException(ErrorResponseCode.JWKS_GENERATION_DISABLE);
        }
        tokenRequest.setCryptoProvider(getKeyGeneratorService().getCryptoProvider());
        tokenRequest.setKeyId(getKeyGeneratorService().getCryptoProvider().getKeyId(getKeyGeneratorService().getKeys(), algorithm, Use.SIGNATURE));
        tokenRequest.setAudience(discoveryResponse.getTokenEndpoint());
    } else {
        tokenRequest.setAuthPassword(rp.getClientSecret());
    }
    final TokenClient tokenClient = getOpClientFactory().createTokenClient(discoveryResponse.getTokenEndpoint());
    tokenClient.setExecutor(getHttpService().getClientEngine());
    tokenClient.setRequest(tokenRequest);
    final TokenResponse response = tokenClient.exec();
    if (response.getStatus() == 200 || response.getStatus() == 302) {
        if (Strings.isNullOrEmpty(response.getIdToken())) {
            LOG.error("id_token is not returned. Please check: 1) OP log file for error (oxauth.log) 2) whether 'openid' scope is present for 'get_authorization_url' command");
            LOG.error("Entity: " + response.getEntity());
            throw new HttpException(ErrorResponseCode.NO_ID_TOKEN_RETURNED);
        }
        if (Strings.isNullOrEmpty(response.getAccessToken())) {
            LOG.error("access_token is not returned");
            throw new HttpException(ErrorResponseCode.NO_ACCESS_TOKEN_RETURNED);
        }
        final Jwt idToken = Jwt.parse(response.getIdToken());
        final Validator validator = new Validator.Builder().discoveryResponse(discoveryResponse).idToken(idToken).keyService(getKeyService()).opClientFactory(getOpClientFactory()).rpServerConfiguration(getConfigurationService().getConfiguration()).rp(rp).build();
        String state = getStateService().encodeExpiredObject(params.getState(), ExpiredObjectType.STATE);
        validator.validateNonce(getStateService());
        validator.validateIdToken();
        validator.validateAccessToken(response.getAccessToken());
        validator.validateState(state);
        // persist tokens
        rp.setIdToken(response.getIdToken());
        rp.setAccessToken(response.getAccessToken());
        getRpService().update(rp);
        getStateService().deleteExpiredObjectsByKey(state);
        LOG.trace("Scope: " + response.getScope());
        final GetTokensByCodeResponse opResponse = new GetTokensByCodeResponse();
        opResponse.setAccessToken(response.getAccessToken());
        opResponse.setIdToken(response.getIdToken());
        opResponse.setRefreshToken(response.getRefreshToken());
        opResponse.setExpiresIn(response.getExpiresIn() != null ? response.getExpiresIn() : -1);
        opResponse.setIdTokenClaims(Jackson2.createJsonMapper().readTree(idToken.getClaims().toJsonString()));
        return opResponse;
    } else {
        if (response.getStatus() == 400) {
            throw new HttpException(ErrorResponseCode.BAD_REQUEST_INVALID_CODE);
        }
        LOG.error("Failed to get tokens because response code is: " + response.getScope());
    }
    return null;
}
Also used : Jwt(io.jans.as.model.jwt.Jwt) AuthenticationMethod(io.jans.as.model.common.AuthenticationMethod) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) Algorithm(io.jans.as.model.jwk.Algorithm) TokenResponse(io.jans.as.client.TokenResponse) TokenRequest(io.jans.as.client.TokenRequest) OpenIdConfigurationResponse(io.jans.as.client.OpenIdConfigurationResponse) HttpException(io.jans.ca.server.HttpException) GetTokensByCodeResponse(io.jans.ca.common.response.GetTokensByCodeResponse) TokenClient(io.jans.as.client.TokenClient) Rp(io.jans.ca.server.service.Rp)

Example 3 with AuthenticationMethod

use of io.jans.as.model.common.AuthenticationMethod in project jans by JanssenProject.

the class GetClientTokenOperation method execute.

@Override
public IOpResponse execute(GetClientTokenParams params) {
    try {
        final AuthenticationMethod authenticationMethod = AuthenticationMethod.fromString(params.getAuthenticationMethod());
        final String tokenEndpoint = getDiscoveryService().getConnectDiscoveryResponse(params.getOpConfigurationEndpoint(), params.getOpHost(), params.getOpDiscoveryPath()).getTokenEndpoint();
        final TokenClient tokenClient = getOpClientFactory().createTokenClient(tokenEndpoint);
        tokenClient.setExecutor(getHttpService().getClientEngine());
        final TokenResponse tokenResponse;
        if (authenticationMethod == AuthenticationMethod.PRIVATE_KEY_JWT) {
            LOG.trace("Getting client token with private_key_jwt client authentication ...");
            SignatureAlgorithm algorithm = SignatureAlgorithm.fromString(params.getAlgorithm());
            if (algorithm == null) {
                throw new HttpException(ErrorResponseCode.INVALID_SIGNATURE_ALGORITHM);
            }
            TokenRequest tokenRequest = new TokenRequest(GrantType.CLIENT_CREDENTIALS);
            tokenRequest.setScope(scopeAsString(params));
            tokenRequest.setAuthUsername(params.getClientId());
            tokenRequest.setAuthenticationMethod(AuthenticationMethod.PRIVATE_KEY_JWT);
            tokenRequest.setAlgorithm(algorithm);
            tokenRequest.setCryptoProvider(getCryptoProvider());
            tokenRequest.setKeyId(params.getKeyId());
            tokenRequest.setAudience(tokenEndpoint);
            tokenClient.setRequest(tokenRequest);
            tokenResponse = tokenClient.exec();
        } else {
            tokenResponse = tokenClient.execClientCredentialsGrant(scopeAsString(params), params.getClientId(), params.getClientSecret());
        }
        if (tokenResponse != null) {
            if (Util.allNotBlank(tokenResponse.getAccessToken())) {
                GetClientTokenResponse response = new GetClientTokenResponse();
                response.setAccessToken(tokenResponse.getAccessToken());
                response.setExpiresIn(tokenResponse.getExpiresIn());
                response.setRefreshToken(tokenResponse.getRefreshToken());
                response.setScope(Utils.stringToList(tokenResponse.getScope()));
                return response;
            } else {
                LOG.error("access_token is blank in response, params: " + params + ", response: " + tokenResponse);
                LOG.error("Please check AS logs for more details (oxauth.log for CE).");
            }
        } else {
            LOG.error("No response from TokenClient");
            LOG.error("Please check AS logs for more details (oxauth.log for CE).");
        }
    } catch (HttpException e) {
        throw e;
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    }
    throw HttpException.internalError();
}
Also used : GetClientTokenResponse(io.jans.ca.common.response.GetClientTokenResponse) TokenResponse(io.jans.as.client.TokenResponse) TokenRequest(io.jans.as.client.TokenRequest) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) HttpException(io.jans.ca.server.HttpException) AuthenticationMethod(io.jans.as.model.common.AuthenticationMethod) GetClientTokenResponse(io.jans.ca.common.response.GetClientTokenResponse) TokenClient(io.jans.as.client.TokenClient) HttpException(io.jans.ca.server.HttpException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 4 with AuthenticationMethod

use of io.jans.as.model.common.AuthenticationMethod in project jans by JanssenProject.

the class RevokeSessionHttpTest method revokeSession.

@Parameters({ "redirectUris", "userId", "userSecret", "redirectUri", "sectorIdentifierUri", "umaPatClientId", "umaPatClientSecret" })
@Test
public void revokeSession(final String redirectUris, final String userId, final String userSecret, final String redirectUri, final String sectorIdentifierUri, String umaPatClientId, String umaPatClientSecret) throws Exception {
    showTitle("revokeSession");
    final AuthenticationMethod authnMethod = AuthenticationMethod.CLIENT_SECRET_BASIC;
    // 1. Register client
    List<ResponseType> responseTypes = Arrays.asList(ResponseType.CODE, ResponseType.ID_TOKEN);
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "jans test app", StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setTokenEndpointAuthMethod(authnMethod);
    registerRequest.setSectorIdentifierUri(sectorIdentifierUri);
    registerRequest.setResponseTypes(responseTypes);
    RegisterClient registerClient = newRegisterClient(registerRequest);
    RegisterResponse registerResponse = registerClient.exec();
    showClient(registerClient);
    assertRegisterResponseOk(registerResponse, 201, true);
    // 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, registerResponse.getClientId(), scopes, redirectUri, nonce);
    authorizationRequest.setState(state);
    AuthorizationResponse authorizationResponse = authenticateResourceOwnerAndGrantAccess(authorizationEndpoint, authorizationRequest, userId, userSecret);
    assertNotNull(authorizationResponse.getLocation(), "The location is null");
    assertNotNull(authorizationResponse.getCode(), "The authorization code is null");
    assertNotNull(authorizationResponse.getIdToken(), "The ID Token is null");
    assertNotNull(authorizationResponse.getState(), "The state is null");
    assertNotNull(authorizationResponse.getScope(), "The scope is null");
    RevokeSessionRequest revokeSessionRequest = new RevokeSessionRequest("uid", "test");
    revokeSessionRequest.setAuthenticationMethod(authnMethod);
    // it must be client with revoke_session scope
    revokeSessionRequest.setAuthUsername(umaPatClientId);
    revokeSessionRequest.setAuthPassword(umaPatClientSecret);
    RevokeSessionClient revokeSessionClient = newRevokeSessionClient(revokeSessionRequest);
    final RevokeSessionResponse revokeSessionResponse = revokeSessionClient.exec();
    showClient(revokeSessionClient);
    assertEquals(revokeSessionResponse.getStatus(), 200);
}
Also used : RegisterRequest(io.jans.as.client.RegisterRequest) AuthorizationRequest(io.jans.as.client.AuthorizationRequest) RevokeSessionRequest(io.jans.as.client.RevokeSessionRequest) AuthenticationMethod(io.jans.as.model.common.AuthenticationMethod) RevokeSessionResponse(io.jans.as.client.RevokeSessionResponse) ResponseType(io.jans.as.model.common.ResponseType) AuthorizationResponse(io.jans.as.client.AuthorizationResponse) RegisterResponse(io.jans.as.client.RegisterResponse) RegisterClient(io.jans.as.client.RegisterClient) RevokeSessionClient(io.jans.as.client.RevokeSessionClient) Parameters(org.testng.annotations.Parameters) BaseTest(io.jans.as.client.BaseTest) Test(org.testng.annotations.Test)

Example 5 with AuthenticationMethod

use of io.jans.as.model.common.AuthenticationMethod in project jans by JanssenProject.

the class ClientAssertion method load.

private boolean load(AppConfiguration appConfiguration, AbstractCryptoProvider cryptoProvider, String clientId, io.jans.as.model.token.ClientAssertionType clientAssertionType, String encodedAssertion) throws Exception {
    boolean result;
    if (clientAssertionType == ClientAssertionType.JWT_BEARER) {
        if (StringUtils.isNotBlank(encodedAssertion)) {
            jwt = Jwt.parse(encodedAssertion);
            // TODO: Store jti this value to check for duplicates
            // Validate clientId
            String issuer = jwt.getClaims().getClaimAsString(JwtClaimName.ISSUER);
            String subject = jwt.getClaims().getClaimAsString(JwtClaimName.SUBJECT_IDENTIFIER);
            List<String> audience = jwt.getClaims().getClaimAsStringList(JwtClaimName.AUDIENCE);
            Date expirationTime = jwt.getClaims().getClaimAsDate(JwtClaimName.EXPIRATION_TIME);
            // SignatureAlgorithm algorithm = SignatureAlgorithm.fromName(jwt.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM));
            if ((clientId == null && StringUtils.isNotBlank(issuer) && StringUtils.isNotBlank(subject) && issuer.equals(subject)) || (StringUtils.isNotBlank(clientId) && StringUtils.isNotBlank(issuer) && StringUtils.isNotBlank(subject) && clientId.equals(issuer) && issuer.equals(subject))) {
                // Validate audience
                String tokenUrl = appConfiguration.getTokenEndpoint();
                String parUrl = StringUtils.isNotBlank(appConfiguration.getParEndpoint()) ? appConfiguration.getParEndpoint() : "";
                String cibaAuthUrl = appConfiguration.getBackchannelAuthenticationEndpoint();
                if (audience != null && (audience.contains(appConfiguration.getIssuer()) || audience.contains(tokenUrl) || audience.contains(parUrl) || audience.contains(cibaAuthUrl))) {
                    // Validate expiration
                    if (expirationTime.after(new Date())) {
                        ClientService clientService = CdiUtil.bean(ClientService.class);
                        Client client = clientService.getClient(subject);
                        // Validate client
                        if (client != null) {
                            JwtType jwtType = JwtType.fromString(jwt.getHeader().getClaimAsString(JwtHeaderName.TYPE));
                            AuthenticationMethod authenticationMethod = client.getAuthenticationMethod();
                            SignatureAlgorithm signatureAlgorithm = jwt.getHeader().getSignatureAlgorithm();
                            if (jwtType == null && signatureAlgorithm != null) {
                                jwtType = signatureAlgorithm.getJwtType();
                            }
                            if (jwtType != null && signatureAlgorithm != null && signatureAlgorithm.getFamily() != null && ((authenticationMethod == AuthenticationMethod.CLIENT_SECRET_JWT && AlgorithmFamily.HMAC.equals(signatureAlgorithm.getFamily())) || (authenticationMethod == AuthenticationMethod.PRIVATE_KEY_JWT && (AlgorithmFamily.RSA.equals(signatureAlgorithm.getFamily()) || AlgorithmFamily.EC.equals(signatureAlgorithm.getFamily()))))) {
                                if (client.getTokenEndpointAuthSigningAlg() == null || SignatureAlgorithm.fromString(client.getTokenEndpointAuthSigningAlg()).equals(signatureAlgorithm)) {
                                    clientSecret = clientService.decryptSecret(client.getClientSecret());
                                    // Validate the crypto segment
                                    String keyId = jwt.getHeader().getKeyId();
                                    JSONObject jwks = Strings.isNullOrEmpty(client.getJwks()) ? JwtUtil.getJSONWebKeys(client.getJwksUri()) : new JSONObject(client.getJwks());
                                    String sharedSecret = clientService.decryptSecret(client.getClientSecret());
                                    boolean validSignature = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(), keyId, jwks, sharedSecret, signatureAlgorithm);
                                    if (validSignature) {
                                        result = true;
                                    } else {
                                        throw new InvalidJwtException("Invalid cryptographic segment");
                                    }
                                } else {
                                    throw new InvalidJwtException("Invalid signing algorithm");
                                }
                            } else {
                                throw new InvalidJwtException("Invalid authentication method");
                            }
                        } else {
                            throw new InvalidJwtException("Invalid client");
                        }
                    } else {
                        throw new InvalidJwtException("JWT has expired");
                    }
                } else {
                    throw new InvalidJwtException("Invalid audience: " + audience);
                }
            } else {
                throw new InvalidJwtException("Invalid clientId");
            }
        } else {
            throw new InvalidJwtException("The Client Assertion is null or empty");
        }
    } else {
        throw new InvalidJwtException("Invalid Client Assertion Type");
    }
    return result;
}
Also used : InvalidJwtException(io.jans.as.model.exception.InvalidJwtException) JSONObject(org.json.JSONObject) ClientService(io.jans.as.server.service.ClientService) JwtType(io.jans.as.model.jwt.JwtType) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) AuthenticationMethod(io.jans.as.model.common.AuthenticationMethod) Client(io.jans.as.common.model.registration.Client) Date(java.util.Date)

Aggregations

AuthenticationMethod (io.jans.as.model.common.AuthenticationMethod)5 SignatureAlgorithm (io.jans.as.model.crypto.signature.SignatureAlgorithm)4 HttpException (io.jans.ca.server.HttpException)3 RegisterRequest (io.jans.as.client.RegisterRequest)2 TokenClient (io.jans.as.client.TokenClient)2 TokenRequest (io.jans.as.client.TokenRequest)2 TokenResponse (io.jans.as.client.TokenResponse)2 AuthorizationRequest (io.jans.as.client.AuthorizationRequest)1 AuthorizationResponse (io.jans.as.client.AuthorizationResponse)1 BaseTest (io.jans.as.client.BaseTest)1 OpenIdConfigurationResponse (io.jans.as.client.OpenIdConfigurationResponse)1 RegisterClient (io.jans.as.client.RegisterClient)1 RegisterResponse (io.jans.as.client.RegisterResponse)1 RevokeSessionClient (io.jans.as.client.RevokeSessionClient)1 RevokeSessionRequest (io.jans.as.client.RevokeSessionRequest)1 RevokeSessionResponse (io.jans.as.client.RevokeSessionResponse)1 Client (io.jans.as.common.model.registration.Client)1 GrantType (io.jans.as.model.common.GrantType)1 ResponseType (io.jans.as.model.common.ResponseType)1 SubjectType (io.jans.as.model.common.SubjectType)1