Search in sources :

Example 1 with UmaPermission

use of io.jans.as.model.uma.persistence.UmaPermission in project jans by JanssenProject.

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<>();
    for (io.jans.as.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 : ArrayList(java.util.ArrayList) UmaPermission(io.jans.as.model.uma.persistence.UmaPermission)

Example 2 with UmaPermission

use of io.jans.as.model.uma.persistence.UmaPermission in project jans by JanssenProject.

the class CleanerTimerTest method umaPermission_whichIsExpiredAndDeletable_MustBeRemoved.

@Test
public void umaPermission_whichIsExpiredAndDeletable_MustBeRemoved() throws StringEncrypter.EncryptionException {
    final Client client = createClient();
    clientService.persist(client);
    final String ticket = UUID.randomUUID().toString();
    // 1. create permission
    UmaPermission permission = new UmaPermission();
    permission.setTicket(ticket);
    permission.setConfigurationCode(UUID.randomUUID().toString());
    permission.setResourceId(UUID.randomUUID().toString());
    umaPermissionService.addPermission(permission, client.getDn());
    // 2. permission exists
    assertNotNull(umaPermissionService.getPermissionsByTicket(ticket).get(0));
    // 3. clean up
    cleanerTimer.processImpl();
    cacheService.clear();
    // 4. permission exists
    assertNotNull(umaPermissionService.getPermissionsByTicket(ticket).get(0));
    final Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.MINUTE, -10);
    permission.setExpirationDate(calendar.getTime());
    umaPermissionService.merge(permission);
    // 5. clean up
    cleanerTimer.processImpl();
    cacheService.clear();
    // 6. no permission in persistence
    final List<UmaPermission> permissionsByTicket = umaPermissionService.getPermissionsByTicket(ticket);
    assertTrue(permissionsByTicket.isEmpty());
}
Also used : Calendar(java.util.Calendar) GregorianCalendar(java.util.GregorianCalendar) UmaPermission(io.jans.as.model.uma.persistence.UmaPermission) Client(io.jans.as.common.model.registration.Client) Test(org.testng.annotations.Test) BaseComponentTest(io.jans.as.server.BaseComponentTest)

Example 3 with UmaPermission

use of io.jans.as.model.uma.persistence.UmaPermission in project jans by JanssenProject.

the class UmaTokenService method addPctToPermissions.

private void addPctToPermissions(List<UmaPermission> permissions, UmaPCT pct) {
    for (UmaPermission p : permissions) {
        p.getAttributes().put(UmaPermission.PCT, pct.getCode());
        permissionService.mergeSilently(p);
    }
}
Also used : UmaPermission(io.jans.as.model.uma.persistence.UmaPermission)

Example 4 with UmaPermission

use of io.jans.as.model.uma.persistence.UmaPermission in project jans by JanssenProject.

the class UmaGatheringWS method gatherClaims.

public Response gatherClaims(String clientId, String ticket, String claimRedirectUri, String state, Boolean authenticationRedirect, HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
    try {
        if (log.isTraceEnabled()) {
            log.trace("gatherClaims client_id: {}, ticket: {}, claims_redirect_uri: {}, state: {}, authenticationRedirect: {}, queryString: {}", escapeLog(clientId), escapeLog(ticket), escapeLog(claimRedirectUri), escapeLog(state), escapeLog(authenticationRedirect), httpRequest.getQueryString());
        }
        errorResponseFactory.validateComponentEnabled(ComponentType.UMA);
        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);
            if (log.isDebugEnabled()) {
                log.debug("Restored parameters from session, clientId: {}, ticket: {}, claims_redirect_uri: {}, state: {}", escapeLog(clientId), escapeLog(ticket), escapeLog(claimRedirectUri), escapeLog(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) {
            if (log.isErrorEnabled()) {
                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(), permissions, clientId, claimRedirectUri, state);
        UmaGatherContext context = new UmaGatherContext(script.getConfigurationAttributes(), httpRequest, session, sessionService, permissionService, pctService, new HashMap<>(), 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: '{}'", step, 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(io.jans.as.server.uma.authorization.UmaWebException) WebApplicationException(javax.ws.rs.WebApplicationException) URI(java.net.URI) UmaWebException(io.jans.as.server.uma.authorization.UmaWebException) WebApplicationException(javax.ws.rs.WebApplicationException) UmaPermission(io.jans.as.model.uma.persistence.UmaPermission) UmaGatherContext(io.jans.as.server.uma.authorization.UmaGatherContext) SessionId(io.jans.as.server.model.common.SessionId) CustomScriptConfiguration(io.jans.model.custom.script.conf.CustomScriptConfiguration)

Example 5 with UmaPermission

use of io.jans.as.model.uma.persistence.UmaPermission in project jans by JanssenProject.

the class UmaRptIntrospectionWS method introspect.

private Response introspect(String authorization, String token, HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
    try {
        errorResponseFactory.validateComponentEnabled(ComponentType.UMA);
        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<io.jans.as.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: {} which is taken from permission object: {}", pctCode, 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(io.jans.as.server.uma.authorization.UmaPCT) ExternalUmaRptClaimsContext(io.jans.as.server.service.external.context.ExternalUmaRptClaimsContext) WebApplicationException(javax.ws.rs.WebApplicationException) WebApplicationException(javax.ws.rs.WebApplicationException) RptIntrospectionResponse(io.jans.as.model.uma.RptIntrospectionResponse) UmaRPT(io.jans.as.server.uma.authorization.UmaRPT) JSONObject(org.json.JSONObject) UmaPermission(io.jans.as.model.uma.persistence.UmaPermission)

Aggregations

UmaPermission (io.jans.as.model.uma.persistence.UmaPermission)10 Scope (io.jans.as.persistence.model.Scope)3 WebApplicationException (javax.ws.rs.WebApplicationException)3 Client (io.jans.as.common.model.registration.Client)2 UmaPCT (io.jans.as.server.uma.authorization.UmaPCT)2 UmaRPT (io.jans.as.server.uma.authorization.UmaRPT)2 UmaScriptByScope (io.jans.as.server.uma.authorization.UmaScriptByScope)2 ArrayList (java.util.ArrayList)2 Jwt (io.jans.as.model.jwt.Jwt)1 RptIntrospectionResponse (io.jans.as.model.uma.RptIntrospectionResponse)1 UmaTokenResponse (io.jans.as.model.uma.UmaTokenResponse)1 BaseComponentTest (io.jans.as.server.BaseComponentTest)1 ExecutionContext (io.jans.as.server.model.common.ExecutionContext)1 SessionId (io.jans.as.server.model.common.SessionId)1 ExternalUmaRptClaimsContext (io.jans.as.server.service.external.context.ExternalUmaRptClaimsContext)1 Claims (io.jans.as.server.uma.authorization.Claims)1 UmaAuthorizationContext (io.jans.as.server.uma.authorization.UmaAuthorizationContext)1 UmaGatherContext (io.jans.as.server.uma.authorization.UmaGatherContext)1 UmaWebException (io.jans.as.server.uma.authorization.UmaWebException)1 CustomScriptConfiguration (io.jans.model.custom.script.conf.CustomScriptConfiguration)1