Search in sources :

Example 11 with ExecutionContext

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

the class OpenIdConfiguration method processRequest.

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param servletRequest servlet request
 * @param httpResponse   servlet response
 * @throws IOException
 */
@SuppressWarnings("deprecation")
protected void processRequest(HttpServletRequest servletRequest, HttpServletResponse httpResponse) throws IOException {
    if (!(externalAuthenticationService.isLoaded() && externalDynamicScopeService.isLoaded())) {
        httpResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        log.error("Jans Auth still starting up!");
        return;
    }
    httpResponse.setContentType("application/json");
    try (PrintWriter out = httpResponse.getWriter()) {
        final JSONObject cachedResponse = localResponseCache.getDiscoveryResponse();
        if (cachedResponse != null) {
            log.trace("Cached discovery response returned.");
            out.println(ServerUtil.toPrettyJson(cachedResponse).replace("\\/", "/"));
            return;
        }
        JSONObject jsonObj = new JSONObject();
        jsonObj.put(ISSUER, appConfiguration.getIssuer());
        jsonObj.put(AUTHORIZATION_ENDPOINT, appConfiguration.getAuthorizationEndpoint());
        jsonObj.put(TOKEN_ENDPOINT, appConfiguration.getTokenEndpoint());
        jsonObj.put(JWKS_URI, appConfiguration.getJwksUri());
        jsonObj.put(CHECK_SESSION_IFRAME, appConfiguration.getCheckSessionIFrame());
        if (appConfiguration.isEnabledComponent(ComponentType.REVOKE_TOKEN))
            jsonObj.put(REVOCATION_ENDPOINT, appConfiguration.getTokenRevocationEndpoint());
        if (appConfiguration.isEnabledComponent(ComponentType.REVOKE_SESSION))
            jsonObj.put(SESSION_REVOCATION_ENDPOINT, endpointUrl("/revoke_session"));
        if (appConfiguration.isEnabledComponent(ComponentType.USERINFO))
            jsonObj.put(USER_INFO_ENDPOINT, appConfiguration.getUserInfoEndpoint());
        if (appConfiguration.isEnabledComponent(ComponentType.CLIENTINFO))
            jsonObj.put(CLIENT_INFO_ENDPOINT, appConfiguration.getClientInfoEndpoint());
        if (appConfiguration.isEnabledComponent(ComponentType.END_SESSION))
            jsonObj.put(END_SESSION_ENDPOINT, appConfiguration.getEndSessionEndpoint());
        if (appConfiguration.isEnabledComponent(ComponentType.REGISTRATION))
            jsonObj.put(REGISTRATION_ENDPOINT, appConfiguration.getRegistrationEndpoint());
        if (appConfiguration.isEnabledComponent(ComponentType.ID_GENERATION))
            jsonObj.put(ID_GENERATION_ENDPOINT, appConfiguration.getIdGenerationEndpoint());
        if (appConfiguration.isEnabledComponent(ComponentType.INTROSPECTION))
            jsonObj.put(INTROSPECTION_ENDPOINT, appConfiguration.getIntrospectionEndpoint());
        if (appConfiguration.isEnabledComponent(ComponentType.DEVICE_AUTHZ))
            jsonObj.put(DEVICE_AUTHZ_ENDPOINT, appConfiguration.getDeviceAuthzEndpoint());
        if (appConfiguration.isEnabledComponent(ComponentType.PAR)) {
            jsonObj.put(PAR_ENDPOINT, appConfiguration.getParEndpoint());
            jsonObj.put(REQUIRE_PAR, appConfiguration.getRequirePar());
        }
        JSONArray responseTypesSupported = new JSONArray();
        for (Set<ResponseType> responseTypes : appConfiguration.getResponseTypesSupported()) {
            responseTypesSupported.put(implode(responseTypes, " "));
        }
        if (responseTypesSupported.length() > 0) {
            jsonObj.put(RESPONSE_TYPES_SUPPORTED, responseTypesSupported);
        }
        JSONArray responseModesSupported = new JSONArray();
        if (appConfiguration.getResponseModesSupported() != null) {
            for (ResponseMode responseMode : appConfiguration.getResponseModesSupported()) {
                responseModesSupported.put(responseMode);
            }
        }
        if (responseModesSupported.length() > 0) {
            jsonObj.put(RESPONSE_MODES_SUPPORTED, responseModesSupported);
        }
        JSONArray grantTypesSupported = new JSONArray();
        for (GrantType grantType : appConfiguration.getGrantTypesSupported()) {
            grantTypesSupported.put(grantType);
        }
        if (grantTypesSupported.length() > 0) {
            jsonObj.put(GRANT_TYPES_SUPPORTED, grantTypesSupported);
        }
        JSONArray acrValuesSupported = new JSONArray();
        for (String acr : externalAuthenticationService.getAcrValuesList()) {
            acrValuesSupported.put(acr);
        }
        jsonObj.put(ACR_VALUES_SUPPORTED, acrValuesSupported);
        jsonObj.put(AUTH_LEVEL_MAPPING, createAuthLevelMapping());
        JSONArray subjectTypesSupported = new JSONArray();
        for (String subjectType : appConfiguration.getSubjectTypesSupported()) {
            subjectTypesSupported.put(subjectType);
        }
        if (subjectTypesSupported.length() > 0) {
            jsonObj.put(SUBJECT_TYPES_SUPPORTED, subjectTypesSupported);
        }
        JSONArray authorizationSigningAlgValuesSupported = new JSONArray();
        for (String authorizationSigningAlg : appConfiguration.getAuthorizationSigningAlgValuesSupported()) {
            authorizationSigningAlgValuesSupported.put(authorizationSigningAlg);
        }
        if (!authorizationSigningAlgValuesSupported.isEmpty()) {
            jsonObj.put(AUTHORIZATION_SIGNING_ALG_VALUES_SUPPORTED, authorizationSigningAlgValuesSupported);
        }
        JSONArray authorizationEncryptionAlgValuesSupported = new JSONArray();
        for (String authorizationEncryptionAlg : appConfiguration.getAuthorizationEncryptionAlgValuesSupported()) {
            authorizationEncryptionAlgValuesSupported.put(authorizationEncryptionAlg);
        }
        if (!authorizationEncryptionAlgValuesSupported.isEmpty()) {
            jsonObj.put(AUTHORIZATION_ENCRYPTION_ALG_VALUES_SUPPORTED, authorizationEncryptionAlgValuesSupported);
        }
        JSONArray authorizationEncryptionEncValuesSupported = new JSONArray();
        for (String authorizationEncyptionEnc : appConfiguration.getAuthorizationEncryptionEncValuesSupported()) {
            authorizationEncryptionEncValuesSupported.put(authorizationEncyptionEnc);
        }
        if (!authorizationEncryptionEncValuesSupported.isEmpty()) {
            jsonObj.put(AUTHORIZATION_ENCRYPTION_ENC_VALUES_SUPPORTED, authorizationEncryptionEncValuesSupported);
        }
        JSONArray userInfoSigningAlgValuesSupported = new JSONArray();
        for (String userInfoSigningAlg : appConfiguration.getUserInfoSigningAlgValuesSupported()) {
            userInfoSigningAlgValuesSupported.put(userInfoSigningAlg);
        }
        if (userInfoSigningAlgValuesSupported.length() > 0) {
            jsonObj.put(USER_INFO_SIGNING_ALG_VALUES_SUPPORTED, userInfoSigningAlgValuesSupported);
        }
        JSONArray userInfoEncryptionAlgValuesSupported = new JSONArray();
        for (String userInfoEncryptionAlg : appConfiguration.getUserInfoEncryptionAlgValuesSupported()) {
            userInfoEncryptionAlgValuesSupported.put(userInfoEncryptionAlg);
        }
        if (userInfoEncryptionAlgValuesSupported.length() > 0) {
            jsonObj.put(USER_INFO_ENCRYPTION_ALG_VALUES_SUPPORTED, userInfoEncryptionAlgValuesSupported);
        }
        JSONArray userInfoEncryptionEncValuesSupported = new JSONArray();
        for (String userInfoEncryptionEnc : appConfiguration.getUserInfoEncryptionEncValuesSupported()) {
            userInfoEncryptionEncValuesSupported.put(userInfoEncryptionEnc);
        }
        if (userInfoEncryptionAlgValuesSupported.length() > 0) {
            jsonObj.put(USER_INFO_ENCRYPTION_ENC_VALUES_SUPPORTED, userInfoEncryptionAlgValuesSupported);
        }
        JSONArray idTokenSigningAlgValuesSupported = new JSONArray();
        for (String idTokenSigningAlg : appConfiguration.getIdTokenSigningAlgValuesSupported()) {
            idTokenSigningAlgValuesSupported.put(idTokenSigningAlg);
        }
        if (idTokenSigningAlgValuesSupported.length() > 0) {
            jsonObj.put(ID_TOKEN_SIGNING_ALG_VALUES_SUPPORTED, idTokenSigningAlgValuesSupported);
        }
        JSONArray idTokenEncryptionAlgValuesSupported = new JSONArray();
        for (String idTokenEncryptionAlg : appConfiguration.getIdTokenEncryptionAlgValuesSupported()) {
            idTokenEncryptionAlgValuesSupported.put(idTokenEncryptionAlg);
        }
        if (idTokenEncryptionAlgValuesSupported.length() > 0) {
            jsonObj.put(ID_TOKEN_ENCRYPTION_ALG_VALUES_SUPPORTED, idTokenEncryptionAlgValuesSupported);
        }
        JSONArray idTokenEncryptionEncValuesSupported = new JSONArray();
        for (String idTokenEncryptionEnc : appConfiguration.getIdTokenEncryptionEncValuesSupported()) {
            idTokenEncryptionEncValuesSupported.put(idTokenEncryptionEnc);
        }
        if (idTokenEncryptionEncValuesSupported.length() > 0) {
            jsonObj.put(ID_TOKEN_ENCRYPTION_ENC_VALUES_SUPPORTED, idTokenEncryptionEncValuesSupported);
        }
        JSONArray requestObjectSigningAlgValuesSupported = new JSONArray();
        for (String requestObjectSigningAlg : appConfiguration.getRequestObjectSigningAlgValuesSupported()) {
            requestObjectSigningAlgValuesSupported.put(requestObjectSigningAlg);
        }
        if (requestObjectSigningAlgValuesSupported.length() > 0) {
            jsonObj.put(REQUEST_OBJECT_SIGNING_ALG_VALUES_SUPPORTED, requestObjectSigningAlgValuesSupported);
        }
        JSONArray requestObjectEncryptionAlgValuesSupported = new JSONArray();
        for (String requestObjectEncryptionAlg : appConfiguration.getRequestObjectEncryptionAlgValuesSupported()) {
            requestObjectEncryptionAlgValuesSupported.put(requestObjectEncryptionAlg);
        }
        if (requestObjectEncryptionAlgValuesSupported.length() > 0) {
            jsonObj.put(REQUEST_OBJECT_ENCRYPTION_ALG_VALUES_SUPPORTED, requestObjectEncryptionAlgValuesSupported);
        }
        JSONArray requestObjectEncryptionEncValuesSupported = new JSONArray();
        for (String requestObjectEncryptionEnc : appConfiguration.getRequestObjectEncryptionEncValuesSupported()) {
            requestObjectEncryptionEncValuesSupported.put(requestObjectEncryptionEnc);
        }
        if (requestObjectEncryptionEncValuesSupported.length() > 0) {
            jsonObj.put(REQUEST_OBJECT_ENCRYPTION_ENC_VALUES_SUPPORTED, requestObjectEncryptionEncValuesSupported);
        }
        JSONArray tokenEndpointAuthMethodsSupported = new JSONArray();
        for (String tokenEndpointAuthMethod : appConfiguration.getTokenEndpointAuthMethodsSupported()) {
            tokenEndpointAuthMethodsSupported.put(tokenEndpointAuthMethod);
        }
        if (tokenEndpointAuthMethodsSupported.length() > 0) {
            jsonObj.put(TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED, tokenEndpointAuthMethodsSupported);
        }
        JSONArray tokenEndpointAuthSigningAlgValuesSupported = new JSONArray();
        for (String tokenEndpointAuthSigningAlg : appConfiguration.getTokenEndpointAuthSigningAlgValuesSupported()) {
            tokenEndpointAuthSigningAlgValuesSupported.put(tokenEndpointAuthSigningAlg);
        }
        if (tokenEndpointAuthSigningAlgValuesSupported.length() > 0) {
            jsonObj.put(TOKEN_ENDPOINT_AUTH_SIGNING_ALG_VALUES_SUPPORTED, tokenEndpointAuthSigningAlgValuesSupported);
        }
        JSONArray dpopSigningAlgValuesSupported = new JSONArray();
        for (String dpopSigningAlg : appConfiguration.getDpopSigningAlgValuesSupported()) {
            dpopSigningAlgValuesSupported.put(dpopSigningAlg);
        }
        if (dpopSigningAlgValuesSupported.length() > 0) {
            jsonObj.put(DPOP_SIGNING_ALG_VALUES_SUPPORTED, dpopSigningAlgValuesSupported);
        }
        JSONArray displayValuesSupported = new JSONArray();
        for (String display : appConfiguration.getDisplayValuesSupported()) {
            displayValuesSupported.put(display);
        }
        if (displayValuesSupported.length() > 0) {
            jsonObj.put(DISPLAY_VALUES_SUPPORTED, displayValuesSupported);
        }
        JSONArray claimTypesSupported = new JSONArray();
        for (String claimType : appConfiguration.getClaimTypesSupported()) {
            claimTypesSupported.put(claimType);
        }
        if (claimTypesSupported.length() > 0) {
            jsonObj.put(CLAIM_TYPES_SUPPORTED, claimTypesSupported);
        }
        jsonObj.put(SERVICE_DOCUMENTATION, appConfiguration.getServiceDocumentation());
        JSONArray idTokenTokenBindingCnfValuesSupported = new JSONArray();
        for (String value : appConfiguration.getIdTokenTokenBindingCnfValuesSupported()) {
            idTokenTokenBindingCnfValuesSupported.put(value);
        }
        jsonObj.put(ID_TOKEN_TOKEN_BINDING_CNF_VALUES_SUPPORTED, idTokenTokenBindingCnfValuesSupported);
        JSONArray claimsLocalesSupported = new JSONArray();
        for (String claimLocale : appConfiguration.getClaimsLocalesSupported()) {
            claimsLocalesSupported.put(claimLocale);
        }
        if (claimsLocalesSupported.length() > 0) {
            jsonObj.put(CLAIMS_LOCALES_SUPPORTED, claimsLocalesSupported);
        }
        JSONArray uiLocalesSupported = new JSONArray();
        for (String uiLocale : appConfiguration.getUiLocalesSupported()) {
            uiLocalesSupported.put(uiLocale);
        }
        if (uiLocalesSupported.length() > 0) {
            jsonObj.put(UI_LOCALES_SUPPORTED, uiLocalesSupported);
        }
        JSONArray scopesSupported = new JSONArray();
        JSONArray claimsSupported = new JSONArray();
        JSONArray scopeToClaimsMapping = createScopeToClaimsMapping(scopesSupported, claimsSupported);
        if (scopesSupported.length() > 0) {
            jsonObj.put(SCOPES_SUPPORTED, scopesSupported);
        }
        if (claimsSupported.length() > 0) {
            jsonObj.put(CLAIMS_SUPPORTED, claimsSupported);
        }
        jsonObj.put(SCOPE_TO_CLAIMS_MAPPING, scopeToClaimsMapping);
        jsonObj.put(CLAIMS_PARAMETER_SUPPORTED, appConfiguration.getClaimsParameterSupported());
        jsonObj.put(REQUEST_PARAMETER_SUPPORTED, appConfiguration.getRequestParameterSupported());
        jsonObj.put(REQUEST_URI_PARAMETER_SUPPORTED, appConfiguration.getRequestUriParameterSupported());
        jsonObj.put(REQUIRE_REQUEST_URI_REGISTRATION, appConfiguration.getRequireRequestUriRegistration());
        jsonObj.put(OP_POLICY_URI, appConfiguration.getOpPolicyUri());
        jsonObj.put(OP_TOS_URI, appConfiguration.getOpTosUri());
        jsonObj.put(TLS_CLIENT_CERTIFICATE_BOUND_ACCESS_TOKENS, Boolean.TRUE);
        jsonObj.put(BACKCHANNEL_LOGOUT_SUPPORTED, Boolean.TRUE);
        jsonObj.put(BACKCHANNEL_LOGOUT_SESSION_SUPPORTED, Boolean.TRUE);
        jsonObj.put(FRONTCHANNEL_LOGOUT_SUPPORTED, Boolean.TRUE);
        jsonObj.put(FRONTCHANNEL_LOGOUT_SESSION_SUPPORTED, Boolean.TRUE);
        jsonObj.put(FRONT_CHANNEL_LOGOUT_SESSION_SUPPORTED, appConfiguration.getFrontChannelLogoutSessionSupported());
        addMtlsAliases(jsonObj);
        // CIBA Configuration
        cibaConfigurationService.processConfiguration(jsonObj);
        filterOutKeys(jsonObj);
        localResponseCache.putDiscoveryResponse(jsonObj);
        JSONObject clone = new JSONObject(jsonObj.toString());
        ExecutionContext context = new ExecutionContext(servletRequest, httpResponse);
        if (!externalDiscoveryService.modifyDiscovery(jsonObj, context)) {
            // revert to original state if object was modified in script
            jsonObj = clone;
        }
        out.println(ServerUtil.toPrettyJson(jsonObj).replace("\\/", "/"));
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}
Also used : ExecutionContext(io.jans.as.server.model.common.ExecutionContext) JSONObject(org.json.JSONObject) ResponseMode(io.jans.as.model.common.ResponseMode) JSONArray(org.json.JSONArray) GrantType(io.jans.as.model.common.GrantType) IOException(java.io.IOException) PrintWriter(java.io.PrintWriter) ResponseType(io.jans.as.model.common.ResponseType)

Example 12 with ExecutionContext

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

the class UmaTokenService method requestRpt.

public Response requestRpt(String grantType, String ticket, String claimToken, String claimTokenFormat, String pctCode, String rptCode, String scope, HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
    try {
        log.trace("requestRpt grant_type: {}, ticket: {}, claim_token: {}, claim_token_format: {}, pct: {}, rpt: {}, scope: {}", grantType, ticket, claimToken, claimTokenFormat, pctCode, rptCode, scope);
        umaValidationService.validateGrantType(grantType);
        List<UmaPermission> permissions = umaValidationService.validateTicket(ticket);
        Jwt idToken = umaValidationService.validateClaimToken(claimToken, claimTokenFormat);
        UmaPCT pct = umaValidationService.validatePct(pctCode);
        UmaRPT rpt = umaValidationService.validateRPT(rptCode);
        Client client = umaValidationService.validate(identity.getSessionClient().getClient());
        Map<Scope, Boolean> scopes = umaValidationService.validateScopes(scope, permissions, client);
        // creates new pct if pct is null in request
        pct = pctService.updateClaims(pct, idToken, client.getClientId(), permissions);
        Claims claims = new Claims(idToken, pct, claimToken);
        Map<UmaScriptByScope, UmaAuthorizationContext> scriptMap = umaNeedsInfoService.checkNeedsInfo(claims, scopes, permissions, pct, httpRequest, client);
        if (!scriptMap.isEmpty()) {
            expressionService.evaluate(scriptMap, permissions);
        } else {
            if (log.isWarnEnabled())
                log.warn("There are no any policies that protects scopes. Scopes: {}. Configuration property umaGrantAccessIfNoPolicies: {}", UmaScopeService.asString(scopes.keySet()), appConfiguration.getUmaGrantAccessIfNoPolicies());
            if (appConfiguration.getUmaGrantAccessIfNoPolicies() != null && appConfiguration.getUmaGrantAccessIfNoPolicies()) {
                log.warn("Access granted because there are no any protection. Make sure it is intentional behavior.");
            } else {
                log.warn("Access denied because there are no any protection. Make sure it is intentional behavior.");
                throw errorResponseFactory.createWebApplicationException(Response.Status.FORBIDDEN, UmaErrorResponseType.FORBIDDEN_BY_POLICY, "Access denied because there are no any protection. Make sure it is intentional behavior.");
            }
        }
        log.trace("Access granted.");
        updatePermissionsWithClientRequestedScope(permissions, scopes);
        addPctToPermissions(permissions, pct);
        boolean upgraded = false;
        if (rpt == null) {
            ExecutionContext executionContext = new ExecutionContext(httpRequest, httpResponse);
            executionContext.setClient(client);
            rpt = rptService.createRPTAndPersist(executionContext, permissions);
            rptCode = rpt.getNotHashedCode();
        } else if (rptService.addPermissionToRPT(rpt, permissions)) {
            upgraded = true;
        }
        UmaTokenResponse response = new UmaTokenResponse();
        response.setAccessToken(rptCode);
        response.setUpgraded(upgraded);
        response.setTokenType("Bearer");
        response.setPct(pct.getCode());
        return Response.ok(ServerUtil.asJson(response)).build();
    } catch (Exception ex) {
        log.error("Exception happened", ex);
        if (ex instanceof WebApplicationException) {
            throw (WebApplicationException) ex;
        }
    }
    log.error("Failed to handle request to UMA Token Endpoint.");
    throw errorResponseFactory.createWebApplicationException(Response.Status.INTERNAL_SERVER_ERROR, UmaErrorResponseType.SERVER_ERROR, "Failed to handle request to UMA Token Endpoint.");
}
Also used : UmaPCT(io.jans.as.server.uma.authorization.UmaPCT) Claims(io.jans.as.server.uma.authorization.Claims) UmaTokenResponse(io.jans.as.model.uma.UmaTokenResponse) WebApplicationException(javax.ws.rs.WebApplicationException) UmaAuthorizationContext(io.jans.as.server.uma.authorization.UmaAuthorizationContext) Jwt(io.jans.as.model.jwt.Jwt) WebApplicationException(javax.ws.rs.WebApplicationException) UmaScriptByScope(io.jans.as.server.uma.authorization.UmaScriptByScope) ExecutionContext(io.jans.as.server.model.common.ExecutionContext) UmaRPT(io.jans.as.server.uma.authorization.UmaRPT) UmaScriptByScope(io.jans.as.server.uma.authorization.UmaScriptByScope) Scope(io.jans.as.persistence.model.Scope) UmaPermission(io.jans.as.model.uma.persistence.UmaPermission) Client(io.jans.as.common.model.registration.Client)

Example 13 with ExecutionContext

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

the class RegisterRestWebServiceImpl method registerClientImpl.

private Response registerClientImpl(String requestParams, HttpServletRequest httpRequest, SecurityContext securityContext) {
    errorResponseFactory.validateComponentEnabled(ComponentType.REGISTRATION);
    Response.ResponseBuilder builder = Response.status(Response.Status.CREATED);
    OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(httpRequest), Action.CLIENT_REGISTRATION);
    try {
        final JSONObject requestObject = parseRequestObjectWithoutValidation(requestParams);
        final JSONObject softwareStatement = validateSoftwareStatement(httpRequest, requestObject);
        if (softwareStatement != null) {
            log.trace("Override request parameters by software_statement");
            for (String key : softwareStatement.keySet()) {
                requestObject.putOpt(key, softwareStatement.get(key));
            }
        }
        if (isTrue(appConfiguration.getDcrSignatureValidationEnabled())) {
            validateRequestObject(requestParams, softwareStatement, httpRequest);
        }
        final RegisterRequest r = RegisterRequest.fromJson(requestObject);
        if (requestObject.has(SOFTWARE_STATEMENT.toString())) {
            r.setSoftwareStatement(requestObject.getString(SOFTWARE_STATEMENT.toString()));
        }
        log.info("Attempting to register client: applicationType = {}, clientName = {}, redirectUris = {}, isSecure = {}, sectorIdentifierUri = {}, defaultAcrValues = {}", r.getApplicationType(), r.getClientName(), r.getRedirectUris(), securityContext.isSecure(), r.getSectorIdentifierUri(), r.getDefaultAcrValues());
        log.trace("Registration request = {}", requestParams);
        if (isFalse(appConfiguration.getDynamicRegistrationPasswordGrantTypeEnabled()) && registerParamsValidator.checkIfThereIsPasswordGrantType(r.getGrantTypes())) {
            log.info("Password Grant Type is not allowed for Dynamic Client Registration.");
            throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.ACCESS_DENIED, "Password Grant Type is not allowed for Dynamic Client Registration.");
        }
        if (isTrue(appConfiguration.getDcrAuthorizationWithClientCredentials()) && !r.getGrantTypes().contains(GrantType.CLIENT_CREDENTIALS)) {
            log.info("Register request does not contain grant_type=client_credentials, however dcrAuthorizationWithClientCredentials=true which is forbidden.");
            throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.ACCESS_DENIED, "Client Credentials Grant Type is not present in Dynamic Client Registration request.");
        }
        if (r.getSubjectType() == null) {
            SubjectType defaultSubjectType = SubjectType.fromString(appConfiguration.getDefaultSubjectType());
            if (defaultSubjectType != null) {
                r.setSubjectType(defaultSubjectType);
            } else if (appConfiguration.getSubjectTypesSupported().contains(io.jans.as.model.common.SubjectType.PUBLIC.toString())) {
                r.setSubjectType(io.jans.as.model.common.SubjectType.PUBLIC);
            } else if (appConfiguration.getSubjectTypesSupported().contains(io.jans.as.model.common.SubjectType.PAIRWISE.toString())) {
                r.setSubjectType(io.jans.as.model.common.SubjectType.PAIRWISE);
            }
        }
        // Throws a WebApplicationException whether a validation doesn't pass
        registerParamsValidator.validateAlgorithms(r);
        // Default Signature Algorithm
        if (r.getIdTokenSignedResponseAlg() == null) {
            r.setIdTokenSignedResponseAlg(SignatureAlgorithm.fromString(appConfiguration.getDefaultSignatureAlgorithm()));
        }
        if (r.getAccessTokenSigningAlg() == null) {
            r.setAccessTokenSigningAlg(SignatureAlgorithm.fromString(appConfiguration.getDefaultSignatureAlgorithm()));
        }
        if (r.getClaimsRedirectUris() != null && !r.getClaimsRedirectUris().isEmpty() && !registerParamsValidator.validateRedirectUris(r.getGrantTypes(), r.getResponseTypes(), r.getApplicationType(), r.getSubjectType(), r.getClaimsRedirectUris(), r.getSectorIdentifierUri())) {
            log.debug("Value of one or more claims_redirect_uris is invalid, claims_redirect_uris: {}", r.getClaimsRedirectUris());
            throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.INVALID_CLAIMS_REDIRECT_URI, "Value of one or more claims_redirect_uris is invalid");
        }
        if (!Strings.isNullOrEmpty(r.getInitiateLoginUri()) && !registerParamsValidator.validateInitiateLoginUri(r.getInitiateLoginUri())) {
            log.debug("The Initiate Login Uri is invalid. The initiate_login_uri must use the https schema: {}", r.getInitiateLoginUri());
            throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.INVALID_CLIENT_METADATA, "The Initiate Login Uri is invalid. The initiate_login_uri must use the https schema.");
        }
        final Pair<Boolean, String> validateResult = registerParamsValidator.validateParamsClientRegister(r.getApplicationType(), r.getSubjectType(), r.getGrantTypes(), r.getResponseTypes(), r.getRedirectUris());
        if (isFalse(validateResult.getFirst())) {
            log.trace("Client parameters are invalid, returns invalid_request error. Reason: {}", validateResult.getSecond());
            throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.INVALID_CLIENT_METADATA, validateResult.getSecond());
        }
        if (!registerParamsValidator.validateRedirectUris(r.getGrantTypes(), r.getResponseTypes(), r.getApplicationType(), r.getSubjectType(), r.getRedirectUris(), r.getSectorIdentifierUri())) {
            throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.INVALID_REDIRECT_URI, "Failed to validate redirect uris.");
        }
        validateSubjectIdentifierAttribute(r);
        if (!cibaRegisterParamsValidatorService.validateParams(r.getBackchannelTokenDeliveryMode(), r.getBackchannelClientNotificationEndpoint(), r.getBackchannelAuthenticationRequestSigningAlg(), r.getGrantTypes(), r.getSubjectType(), r.getSectorIdentifierUri(), r.getJwks(), r.getJwksUri())) {
            // CIBA
            throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.INVALID_CLIENT_METADATA, "Invalid Client Metadata registering to use CIBA (Client Initiated Backchannel Authentication).");
        }
        registerParamsValidator.validateLogoutUri(r.getFrontChannelLogoutUri(), r.getRedirectUris(), errorResponseFactory);
        registerParamsValidator.validateLogoutUri(r.getBackchannelLogoutUris(), r.getRedirectUris(), errorResponseFactory);
        String clientsBaseDN = staticConfiguration.getBaseDn().getClients();
        String inum = inumService.generateClientInum();
        String generatedClientSecret = UUID.randomUUID().toString();
        final Client client = new Client();
        client.setDn("inum=" + inum + "," + clientsBaseDN);
        client.setClientId(inum);
        client.setDeletable(true);
        client.setClientSecret(clientService.encryptSecret(generatedClientSecret));
        client.setRegistrationAccessToken(HandleTokenFactory.generateHandleToken());
        client.setIdTokenTokenBindingCnf(r.getIdTokenTokenBindingCnf());
        final Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
        client.setClientIdIssuedAt(calendar.getTime());
        if (appConfiguration.getDynamicRegistrationExpirationTime() > 0) {
            // #883 : expiration can be -1, mean does not expire
            calendar.add(Calendar.SECOND, appConfiguration.getDynamicRegistrationExpirationTime());
            client.setClientSecretExpiresAt(calendar.getTime());
            client.setExpirationDate(calendar.getTime());
            client.setTtl(appConfiguration.getDynamicRegistrationExpirationTime());
        }
        client.setDeletable(client.getClientSecretExpiresAt() != null);
        setClientName(r, client);
        updateClientFromRequestObject(client, r, false);
        boolean registerClient = true;
        if (externalDynamicClientRegistrationService.isEnabled()) {
            registerClient = externalDynamicClientRegistrationService.executeExternalCreateClientMethods(r, client, httpRequest);
        }
        if (!registerClient) {
            // clear cache to force reload from persistence
            clientService.removeFromCache(client);
            log.trace("Client parameters are invalid, returns invalid_request error. External registration script returned false.");
            throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.INVALID_CLIENT_METADATA, "External registration script returned false.");
        }
        Date currentTime = Calendar.getInstance().getTime();
        client.setLastAccessTime(currentTime);
        client.setLastLogonTime(currentTime);
        client.setPersistClientAuthorizations(isTrue(appConfiguration.getDynamicRegistrationPersistClientAuthorizations()));
        clientService.persist(client);
        JSONObject jsonObject = getJSONObject(client);
        jsonObject = modifyPostScript(jsonObject, new ExecutionContext(httpRequest, null).setClient(client));
        builder.entity(jsonObjectToString(jsonObject));
        log.info("Client registered: clientId = {}, applicationType = {}, clientName = {}, redirectUris = {}, sectorIdentifierUri = {}", client.getClientId(), client.getApplicationType(), client.getClientName(), client.getRedirectUris(), client.getSectorIdentifierUri());
        oAuth2AuditLog.setClientId(client.getClientId());
        oAuth2AuditLog.setScope(clientScopesToString(client));
        oAuth2AuditLog.setSuccess(true);
    } catch (StringEncrypter.EncryptionException e) {
        builder = internalErrorResponse("Encryption exception occured.");
        log.error(e.getMessage(), e);
    } catch (JSONException e) {
        builder = internalErrorResponse("Failed to parse JSON.");
        log.error(e.getMessage(), e);
    } catch (WebApplicationException e) {
        if (log.isErrorEnabled())
            log.error(e.getMessage(), e);
        throw e;
    } catch (Exception e) {
        builder = internalErrorResponse(Constants.UNKNOWN_DOT);
        log.error(e.getMessage(), e);
    }
    builder.cacheControl(ServerUtil.cacheControl(true, false));
    builder.header(Constants.PRAGMA, Constants.NO_CACHE);
    builder.type(MediaType.APPLICATION_JSON_TYPE);
    applicationAuditLogger.sendMessage(oAuth2AuditLog);
    return builder.build();
}
Also used : RegisterRequest(io.jans.as.client.RegisterRequest) WebApplicationException(javax.ws.rs.WebApplicationException) OAuth2AuditLog(io.jans.as.server.model.audit.OAuth2AuditLog) JSONException(org.json.JSONException) StringEncrypter(io.jans.util.security.StringEncrypter) JSONException(org.json.JSONException) InvalidJwtException(io.jans.as.model.exception.InvalidJwtException) WebApplicationException(javax.ws.rs.WebApplicationException) Response(javax.ws.rs.core.Response) ExecutionContext(io.jans.as.server.model.common.ExecutionContext) JSONObject(org.json.JSONObject) Client(io.jans.as.common.model.registration.Client)

Example 14 with ExecutionContext

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

the class RegisterRestWebServiceImpl method requestClientUpdate.

@Override
public Response requestClientUpdate(String requestParams, String clientId, @HeaderParam("Authorization") String authorization, @Context HttpServletRequest httpRequest, @Context SecurityContext securityContext) {
    errorResponseFactory.validateComponentEnabled(ComponentType.REGISTRATION);
    OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(httpRequest), Action.CLIENT_UPDATE);
    oAuth2AuditLog.setClientId(clientId);
    try {
        log.debug("Attempting to UPDATE client, client_id: {}, requestParams = {}, isSecure = {}", clientId, requestParams, securityContext.isSecure());
        final String accessToken = tokenService.getToken(authorization);
        if (StringUtils.isNotBlank(accessToken) && StringUtils.isNotBlank(clientId) && StringUtils.isNotBlank(requestParams)) {
            validateAuthorizationAccessToken(accessToken, clientId);
            final JSONObject requestObject = parseRequestObjectWithoutValidation(requestParams);
            final JSONObject softwareStatement = validateSoftwareStatement(httpRequest, requestObject);
            if (softwareStatement != null) {
                log.trace("Override request parameters by software_statement");
                for (String key : softwareStatement.keySet()) {
                    requestObject.putOpt(key, softwareStatement.get(key));
                }
            }
            if (isTrue(appConfiguration.getDcrSignatureValidationEnabled())) {
                validateRequestObject(requestParams, softwareStatement, httpRequest);
            }
            final RegisterRequest request = RegisterRequest.fromJson(requestParams);
            boolean redirectUrisValidated = true;
            if (request.getRedirectUris() != null && !request.getRedirectUris().isEmpty()) {
                redirectUrisValidated = registerParamsValidator.validateRedirectUris(request.getGrantTypes(), request.getResponseTypes(), request.getApplicationType(), request.getSubjectType(), request.getRedirectUris(), request.getSectorIdentifierUri());
            }
            if (redirectUrisValidated) {
                if (!cibaRegisterParamsValidatorService.validateParams(request.getBackchannelTokenDeliveryMode(), request.getBackchannelClientNotificationEndpoint(), request.getBackchannelAuthenticationRequestSigningAlg(), request.getGrantTypes(), request.getSubjectType(), request.getSectorIdentifierUri(), request.getJwks(), request.getJwksUri())) {
                    return Response.status(Response.Status.BAD_REQUEST).entity(errorResponseFactory.errorAsJson(RegisterErrorResponseType.INVALID_CLIENT_METADATA, "Invalid Client Metadata registering to use CIBA.")).build();
                }
                if (request.getSubjectType() != null && !appConfiguration.getSubjectTypesSupported().contains(request.getSubjectType().toString())) {
                    log.debug("Client UPDATE : parameter subject_type is invalid. Returns BAD_REQUEST response.");
                    applicationAuditLogger.sendMessage(oAuth2AuditLog);
                    return Response.status(Response.Status.BAD_REQUEST).entity(errorResponseFactory.errorAsJson(RegisterErrorResponseType.INVALID_CLIENT_METADATA, "subject_type is invalid.")).build();
                }
                final Client client = clientService.getClient(clientId, accessToken);
                if (client != null) {
                    updateClientFromRequestObject(client, request, true);
                    boolean updateClient = true;
                    if (externalDynamicClientRegistrationService.isEnabled()) {
                        updateClient = externalDynamicClientRegistrationService.executeExternalUpdateClientMethods(httpRequest, request, client);
                    }
                    if (updateClient) {
                        clientService.merge(client);
                        JSONObject jsonObject = getJSONObject(client);
                        jsonObject = modifyPutScript(jsonObject, new ExecutionContext(httpRequest, null).setClient(client));
                        final Response response = Response.ok().entity(jsonObjectToString(jsonObject)).build();
                        oAuth2AuditLog.setScope(clientScopesToString(client));
                        oAuth2AuditLog.setSuccess(true);
                        applicationAuditLogger.sendMessage(oAuth2AuditLog);
                        return response;
                    } else {
                        // clear cache to force reload from persistence
                        clientService.removeFromCache(client);
                        log.trace("The Access Token is not valid for the Client ID, returns invalid_token error, client_id: {}", clientId);
                        applicationAuditLogger.sendMessage(oAuth2AuditLog);
                        return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(errorResponseFactory.errorAsJson(RegisterErrorResponseType.INVALID_TOKEN, "External registration script returned false.")).build();
                    }
                } else {
                    log.trace("The Access Token is not valid for the Client ID, returns invalid_token error.");
                    applicationAuditLogger.sendMessage(oAuth2AuditLog);
                    return Response.status(Response.Status.UNAUTHORIZED).type(MediaType.APPLICATION_JSON_TYPE).entity(errorResponseFactory.errorAsJson(RegisterErrorResponseType.INVALID_TOKEN, "The Access Token is not valid for the Client ID.")).build();
                }
            }
        }
        log.debug("Client UPDATE : parameters are invalid. Returns BAD_REQUEST response.");
        applicationAuditLogger.sendMessage(oAuth2AuditLog);
        return Response.status(Response.Status.BAD_REQUEST).entity(errorResponseFactory.errorAsJson(RegisterErrorResponseType.INVALID_CLIENT_METADATA, Constants.UNKNOWN_DOT)).build();
    } catch (WebApplicationException e) {
        if (log.isErrorEnabled())
            log.error(e.getMessage(), e);
        throw e;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    applicationAuditLogger.sendMessage(oAuth2AuditLog);
    return internalErrorResponse(Constants.UNKNOWN_DOT).build();
}
Also used : Response(javax.ws.rs.core.Response) RegisterRequest(io.jans.as.client.RegisterRequest) ExecutionContext(io.jans.as.server.model.common.ExecutionContext) JSONObject(org.json.JSONObject) WebApplicationException(javax.ws.rs.WebApplicationException) OAuth2AuditLog(io.jans.as.server.model.audit.OAuth2AuditLog) Client(io.jans.as.common.model.registration.Client) JSONException(org.json.JSONException) InvalidJwtException(io.jans.as.model.exception.InvalidJwtException) WebApplicationException(javax.ws.rs.WebApplicationException)

Example 15 with ExecutionContext

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

the class RevokeRestWebServiceImpl method requestAccessToken.

@Override
public Response requestAccessToken(String tokenString, String tokenTypeHint, String clientId, HttpServletRequest request, HttpServletResponse response, SecurityContext sec) {
    log.debug("Attempting to revoke token: token = {}, tokenTypeHint = {}, isSecure = {}", tokenString, tokenTypeHint, sec.isSecure());
    errorResponseFactory.validateComponentEnabled(ComponentType.REVOKE_TOKEN);
    OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(request), Action.TOKEN_REVOCATION);
    validateToken(tokenString);
    Response.ResponseBuilder builder = Response.ok();
    SessionClient sessionClient = identity.getSessionClient();
    Client client = sessionClient != null ? sessionClient.getClient() : null;
    if (client == null) {
        client = clientService.getClient(clientId);
        if (!clientService.isPublic(client)) {
            log.trace("Client is not public and not authenticated. Skip revoking.");
            return response(builder, oAuth2AuditLog);
        }
    }
    if (client == null) {
        log.trace("Client is not unknown. Skip revoking.");
        return response(builder, oAuth2AuditLog);
    }
    oAuth2AuditLog.setClientId(client.getClientId());
    ExecutionContext executionContext = new ExecutionContext(request, response);
    executionContext.setClient(client);
    executionContext.setResponseBuilder(builder);
    final boolean scriptResult = externalRevokeTokenService.revokeTokenMethods(executionContext);
    if (!scriptResult) {
        log.trace("Revoke is forbidden by 'Revoke Token' custom script (method returned false). Exit without revoking.");
        return response(builder, oAuth2AuditLog);
    }
    TokenTypeHint tth = TokenTypeHint.getByValue(tokenTypeHint);
    boolean isAll = Constants.ALL.equalsIgnoreCase(tokenString) && appConfiguration.getAllowAllValueForRevokeEndpoint();
    if (isAll) {
        removeAllTokens(tth, executionContext);
        return response(builder, oAuth2AuditLog);
    }
    String[] tokens = tokenString.split(" ");
    if (ArrayUtils.isEmpty(tokens)) {
        throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST.getStatusCode()).type(MediaType.APPLICATION_JSON_TYPE).entity(errorResponseFactory.errorAsJson(TokenRevocationErrorResponseType.INVALID_REQUEST, "Failed to validate token.")).build());
    }
    boolean isSingle = tokens.length == 1;
    for (String token : tokens) {
        final Response removeTokenResponse = removeToken(token, executionContext, tth, oAuth2AuditLog, isSingle);
        if (removeTokenResponse != null) {
            return removeTokenResponse;
        }
    }
    return response(builder, oAuth2AuditLog);
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(javax.ws.rs.core.Response) ExecutionContext(io.jans.as.server.model.common.ExecutionContext) WebApplicationException(javax.ws.rs.WebApplicationException) SessionClient(io.jans.as.server.model.session.SessionClient) OAuth2AuditLog(io.jans.as.server.model.audit.OAuth2AuditLog) TokenTypeHint(io.jans.as.model.common.TokenTypeHint) Client(io.jans.as.common.model.registration.Client) SessionClient(io.jans.as.server.model.session.SessionClient)

Aggregations

ExecutionContext (io.jans.as.server.model.common.ExecutionContext)16 Client (io.jans.as.common.model.registration.Client)8 JSONObject (org.json.JSONObject)8 WebApplicationException (javax.ws.rs.WebApplicationException)7 OAuth2AuditLog (io.jans.as.server.model.audit.OAuth2AuditLog)5 Response (javax.ws.rs.core.Response)5 JSONException (org.json.JSONException)4 Test (org.testng.annotations.Test)4 InvalidJwtException (io.jans.as.model.exception.InvalidJwtException)3 AccessToken (io.jans.as.server.model.common.AccessToken)3 RegisterRequest (io.jans.as.client.RegisterRequest)2 User (io.jans.as.common.model.common.User)2 GrantType (io.jans.as.model.common.GrantType)2 Jwt (io.jans.as.model.jwt.Jwt)2 AuthorizationGrant (io.jans.as.server.model.common.AuthorizationGrant)2 ClientCredentialsGrant (io.jans.as.server.model.common.ClientCredentialsGrant)2 SessionId (io.jans.as.server.model.common.SessionId)2 SessionClient (io.jans.as.server.model.session.SessionClient)2 ExternalUpdateTokenContext (io.jans.as.server.service.external.context.ExternalUpdateTokenContext)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2