Search in sources :

Example 1 with UmaPermission

use of org.gluu.oxauth.model.uma.persistence.UmaPermission in project oxAuth by GluuFederation.

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 {
            log.warn("There are no any policies that protects scopes. Scopes: " + UmaScopeService.asString(scopes.keySet()) + ". Configuration property umaGrantAccessIfNoPolicies: " + 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 : UmaTokenResponse(org.gluu.oxauth.model.uma.UmaTokenResponse) WebApplicationException(javax.ws.rs.WebApplicationException) Jwt(org.gluu.oxauth.model.jwt.Jwt) WebApplicationException(javax.ws.rs.WebApplicationException) ExecutionContext(org.gluu.oxauth.model.common.ExecutionContext) Scope(org.oxauth.persistence.model.Scope) UmaPermission(org.gluu.oxauth.model.uma.persistence.UmaPermission) Client(org.gluu.oxauth.model.registration.Client)

Example 2 with UmaPermission

use of org.gluu.oxauth.model.uma.persistence.UmaPermission in project oxAuth by GluuFederation.

the class UmaValidationService method validateScopes.

/**
 * @param scope scope string from token request
 * @param permissions permissions
 * @return map of loaded scope and boolean, true - if client requested scope and false if it is permission ticket scope
 */
public Map<Scope, Boolean> validateScopes(String scope, List<UmaPermission> permissions, Client client) {
    scope = ServerUtil.urlDecode(scope);
    final String[] scopesRequested = StringUtils.isNotBlank(scope) ? scope.split(" ") : new String[0];
    final Map<Scope, Boolean> result = new HashMap<Scope, Boolean>();
    if (ArrayUtils.isNotEmpty(scopesRequested)) {
        final Set<String> resourceScopes = resourceService.getResourceScopes(permissions.stream().map(UmaPermission::getResourceId).collect(Collectors.toSet()));
        for (String scopeId : scopesRequested) {
            final Scope ldapScope = umaScopeService.getOrCreate(client, scopeId, resourceScopes);
            if (ldapScope != null) {
                result.put(ldapScope, true);
            } else {
                log.trace("Skip requested scope because it's not allowed, scope: " + scopeId);
            }
        }
    }
    for (UmaPermission permission : permissions) {
        for (Scope s : umaScopeService.getScopesByDns(permission.getScopeDns())) {
            result.put(s, false);
        }
    }
    if (result.isEmpty()) {
        log.error("There are no any scopes requested in the request.");
        throw errorResponseFactory.createWebApplicationException(BAD_REQUEST, UmaErrorResponseType.INVALID_SCOPE, "There are no any scopes requested in give request.");
    }
    log.trace("CandidateGrantedScopes: " + Joiner.on(", ").join(Iterables.transform(result.keySet(), new Function<Scope, String>() {

        @Override
        public String apply(Scope scope) {
            return scope.getId();
        }
    })));
    return result;
}
Also used : Function(org.python.google.common.base.Function) Scope(org.oxauth.persistence.model.Scope) UmaPermission(org.gluu.oxauth.model.uma.persistence.UmaPermission)

Example 3 with UmaPermission

use of org.gluu.oxauth.model.uma.persistence.UmaPermission in project oxAuth by GluuFederation.

the class UmaGatheringWS method gatherClaims.

public Response gatherClaims(String clientId, String ticket, String claimRedirectUri, String state, Boolean reset, Boolean authenticationRedirect, HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
    try {
        log.trace("gatherClaims client_id: {}, ticket: {}, claims_redirect_uri: {}, state: {}, authenticationRedirect: {}, queryString: {}", clientId, ticket, claimRedirectUri, state, authenticationRedirect, httpRequest.getQueryString());
        SessionId session = sessionService.getSession(httpRequest, httpResponse);
        if (authenticationRedirect != null && authenticationRedirect) {
            // restore parameters from session
            log.debug("Authentication redirect, restoring parameters from session ...");
            if (session == null) {
                log.error("Session is null however authentication=true. Wrong workflow! Please correct custom Glaims-Gathering Script.");
                throw errorResponseFactory.createWebApplicationException(BAD_REQUEST, INVALID_SESSION, "Session is null however authentication=true. Wrong workflow! Please correct custom Glaims-Gathering Script.");
            }
            clientId = sessionService.getClientId(session);
            ticket = sessionService.getTicket(session);
            claimRedirectUri = sessionService.getClaimsRedirectUri(session);
            state = sessionService.getState(session);
            log.debug("Restored parameters from session, clientId: {}, ticket: {}, claims_redirect_uri: {}, state: {}", clientId, ticket, claimRedirectUri, state);
        }
        validationService.validateClientAndClaimsRedirectUri(clientId, claimRedirectUri, state);
        List<UmaPermission> permissions = validationService.validateTicketWithRedirect(ticket, claimRedirectUri, state);
        String[] scriptNames = validationService.validatesGatheringScriptNames(getScriptNames(permissions), claimRedirectUri, state);
        CustomScriptConfiguration script = external.determineScript(scriptNames);
        if (script == null) {
            log.error("Failed to determine claims-gathering script for names: " + Arrays.toString(scriptNames));
            throw new UmaWebException(claimRedirectUri, errorResponseFactory, INVALID_CLAIMS_GATHERING_SCRIPT_NAME, state);
        }
        sessionService.configure(session, script.getName(), reset, permissions, clientId, claimRedirectUri, state);
        UmaGatherContext context = new UmaGatherContext(script.getConfigurationAttributes(), httpRequest, session, sessionService, permissionService, pctService, new HashMap<String, String>(), userService, null, appConfiguration);
        int step = sessionService.getStep(session);
        int stepsCount = external.getStepsCount(script, context);
        if (step < stepsCount) {
            String page = external.getPageForStep(script, step, context);
            context.persist();
            String baseEndpoint = StringUtils.removeEnd(appConfiguration.getBaseEndpoint(), "/");
            baseEndpoint = StringUtils.removeEnd(baseEndpoint, "restv1");
            baseEndpoint = StringUtils.removeEnd(baseEndpoint, "/");
            String fullUri = baseEndpoint + page;
            fullUri = StringUtils.removeEnd(fullUri, ".xhtml") + ".htm";
            log.trace("Redirecting to page: '{}', fullUri: {}", page, fullUri);
            return Response.status(FOUND).location(new URI(fullUri)).build();
        } else {
            log.error("Step '{}' is more or equal to stepCount: '{}'", stepsCount);
        }
    } catch (Exception ex) {
        log.error("Exception happened", ex);
        if (ex instanceof WebApplicationException) {
            throw (WebApplicationException) ex;
        }
    }
    log.error("Failed to handle call to UMA Claims Gathering Endpoint.");
    throw errorResponseFactory.createWebApplicationException(Response.Status.INTERNAL_SERVER_ERROR, UmaErrorResponseType.SERVER_ERROR, "Failed to handle call to UMA Claims Gathering Endpoint.");
}
Also used : UmaWebException(org.gluu.oxauth.uma.authorization.UmaWebException) URI(java.net.URI) UmaWebException(org.gluu.oxauth.uma.authorization.UmaWebException) UmaPermission(org.gluu.oxauth.model.uma.persistence.UmaPermission) UmaGatherContext(org.gluu.oxauth.uma.authorization.UmaGatherContext) SessionId(org.gluu.oxauth.model.common.SessionId) CustomScriptConfiguration(org.gluu.model.custom.script.conf.CustomScriptConfiguration)

Example 4 with UmaPermission

use of org.gluu.oxauth.model.uma.persistence.UmaPermission in project oxAuth by GluuFederation.

the class UmaRptIntrospectionWS method introspect.

private Response introspect(String authorization, String token, String tokenTypeHint, HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
    try {
        umaValidationService.assertHasProtectionScope(authorization);
        final UmaRPT rpt = rptService.getRPTByCode(token);
        if (!isValid(rpt)) {
            return Response.status(Response.Status.OK).entity(new RptIntrospectionResponse(false)).cacheControl(ServerUtil.cacheControl(true)).build();
        }
        final List<org.gluu.oxauth.model.uma.UmaPermission> permissions = buildStatusResponsePermissions(rpt);
        // active status
        final RptIntrospectionResponse statusResponse = new RptIntrospectionResponse();
        statusResponse.setActive(true);
        statusResponse.setExpiresAt(ServerUtil.dateToSeconds(rpt.getExpirationDate()));
        statusResponse.setIssuedAt(ServerUtil.dateToSeconds(rpt.getCreationDate()));
        statusResponse.setPermissions(permissions);
        statusResponse.setClientId(rpt.getClientId());
        statusResponse.setAud(rpt.getClientId());
        statusResponse.setSub(rpt.getUserId());
        final List<UmaPermission> rptPermissions = rptService.getRptPermissions(rpt);
        if (!rptPermissions.isEmpty()) {
            UmaPermission permission = rptPermissions.iterator().next();
            String pctCode = permission.getAttributes().get(UmaPermission.PCT);
            if (StringHelper.isNotEmpty(pctCode)) {
                UmaPCT pct = pctService.getByCode(pctCode);
                if (pct != null) {
                    statusResponse.setPctClaims(pct.getClaims().toMap());
                } else {
                    log.error("Failed to find PCT with code: " + pctCode + " which is taken from permission object: " + permission.getDn());
                }
            } else {
                log.trace("PCT code is blank for RPT: " + rpt.getCode());
            }
        }
        JSONObject rptAsJson = new JSONObject(ServerUtil.asJson(statusResponse));
        ExternalUmaRptClaimsContext context = new ExternalUmaRptClaimsContext(clientService.getClient(rpt.getClientId()), httpRequest, httpResponse);
        if (externalUmaRptClaimsService.externalModify(rptAsJson, context)) {
            log.trace("Successfully run external RPT Claims script associated with {}", rpt.getClientId());
        } else {
            rptAsJson = new JSONObject(ServerUtil.asJson(statusResponse));
            log.trace("Canceled changes made by external RPT Claims script since method returned `false`.");
        }
        return Response.status(Response.Status.OK).entity(rptAsJson.toString()).type(MediaType.APPLICATION_JSON_TYPE).cacheControl(ServerUtil.cacheControl(true)).build();
    } catch (Exception ex) {
        log.error("Exception happened", ex);
        if (ex instanceof WebApplicationException) {
            throw (WebApplicationException) ex;
        }
        throw errorResponseFactory.createWebApplicationException(Response.Status.INTERNAL_SERVER_ERROR, UmaErrorResponseType.SERVER_ERROR, "Internal error.");
    }
}
Also used : UmaPCT(org.gluu.oxauth.uma.authorization.UmaPCT) ExternalUmaRptClaimsContext(org.gluu.oxauth.service.external.context.ExternalUmaRptClaimsContext) RptIntrospectionResponse(org.gluu.oxauth.model.uma.RptIntrospectionResponse) UmaRPT(org.gluu.oxauth.uma.authorization.UmaRPT) JSONObject(org.json.JSONObject) UmaPermission(org.gluu.oxauth.model.uma.persistence.UmaPermission)

Example 5 with UmaPermission

use of org.gluu.oxauth.model.uma.persistence.UmaPermission in project oxAuth by GluuFederation.

the class UmaPermissionService method createPermissions.

private List<UmaPermission> createPermissions(UmaPermissionList permissions, Pair<Date, Integer> expirationDate) {
    final String configurationCode = INumGenerator.generate(8) + "." + System.currentTimeMillis();
    final String ticket = generateNewTicket();
    List<UmaPermission> result = new ArrayList<UmaPermission>();
    for (org.gluu.oxauth.model.uma.UmaPermission permission : permissions) {
        UmaPermission p = new UmaPermission(permission.getResourceId(), scopeService.getScopeDNsByIdsAndAddToLdapIfNeeded(permission.getScopes()), ticket, configurationCode, expirationDate);
        if (permission.getParams() != null && !permission.getParams().isEmpty()) {
            p.getAttributes().putAll(permission.getParams());
        }
        result.add(p);
    }
    return result;
}
Also used : UmaPermission(org.gluu.oxauth.model.uma.persistence.UmaPermission)

Aggregations

UmaPermission (org.gluu.oxauth.model.uma.persistence.UmaPermission)10 Scope (org.oxauth.persistence.model.Scope)3 Client (org.gluu.oxauth.model.registration.Client)2 URI (java.net.URI)1 WebApplicationException (javax.ws.rs.WebApplicationException)1 CustomScriptConfiguration (org.gluu.model.custom.script.conf.CustomScriptConfiguration)1 BaseComponentTest (org.gluu.oxauth.BaseComponentTest)1 ExecutionContext (org.gluu.oxauth.model.common.ExecutionContext)1 SessionId (org.gluu.oxauth.model.common.SessionId)1 Jwt (org.gluu.oxauth.model.jwt.Jwt)1 RptIntrospectionResponse (org.gluu.oxauth.model.uma.RptIntrospectionResponse)1 UmaTokenResponse (org.gluu.oxauth.model.uma.UmaTokenResponse)1 ExternalUmaRptClaimsContext (org.gluu.oxauth.service.external.context.ExternalUmaRptClaimsContext)1 UmaGatherContext (org.gluu.oxauth.uma.authorization.UmaGatherContext)1 UmaPCT (org.gluu.oxauth.uma.authorization.UmaPCT)1 UmaRPT (org.gluu.oxauth.uma.authorization.UmaRPT)1 UmaWebException (org.gluu.oxauth.uma.authorization.UmaWebException)1 JSONArray (org.json.JSONArray)1 JSONObject (org.json.JSONObject)1 Function (org.python.google.common.base.Function)1