Search in sources :

Example 1 with RealmContext

use of org.forgerock.openam.rest.RealmContext in project OpenAM by OpenRock.

the class AuditRestRouteProvider method addResourceRoutes.

@Override
public void addResourceRoutes(ResourceRouter rootRouter, ResourceRouter realmRouter) {
    rootRouter.route("global-audit").auditAs(AUDIT, AuditEndpointAuditFilter.class).authorizeWith(SpecialOrAdminOrAgentAuthzModule.class).forVersion(1).toRequestHandler(STARTS_WITH, auditServiceProvider.getDefaultAuditService());
    rootRouter.route("realm-audit").auditAs(AUDIT, AuditEndpointAuditFilter.class).authorizeWith(SpecialOrAdminOrAgentAuthzModule.class).forVersion(1).through(RealmContextFilter.class).toRequestHandler(STARTS_WITH, new RequestHandler() {

        @Override
        public Promise<ActionResponse, ResourceException> handleAction(Context context, ActionRequest actionRequest) {
            return getAuditService(context).handleAction(context, actionRequest);
        }

        @Override
        public Promise<ResourceResponse, ResourceException> handleCreate(Context context, CreateRequest createRequest) {
            return getAuditService(context).handleCreate(context, createRequest);
        }

        @Override
        public Promise<ResourceResponse, ResourceException> handleDelete(Context context, DeleteRequest deleteRequest) {
            return getAuditService(context).handleDelete(context, deleteRequest);
        }

        @Override
        public Promise<ResourceResponse, ResourceException> handlePatch(Context context, PatchRequest patchRequest) {
            return getAuditService(context).handlePatch(context, patchRequest);
        }

        @Override
        public Promise<QueryResponse, ResourceException> handleQuery(Context context, QueryRequest queryRequest, QueryResourceHandler queryResourceHandler) {
            return getAuditService(context).handleQuery(context, queryRequest, queryResourceHandler);
        }

        @Override
        public Promise<ResourceResponse, ResourceException> handleRead(Context context, ReadRequest readRequest) {
            return getAuditService(context).handleRead(context, readRequest);
        }

        @Override
        public Promise<ResourceResponse, ResourceException> handleUpdate(Context context, UpdateRequest updateRequest) {
            return getAuditService(context).handleUpdate(context, updateRequest);
        }

        private AMAuditService getAuditService(Context context) {
            String realm = context.asContext(RealmContext.class).getResolvedRealm();
            if (StringUtils.isEmpty(realm)) {
                logger.warn("Context contained RealmContext but had an empty resolved realm");
                return auditServiceProvider.getDefaultAuditService();
            }
            return auditServiceProvider.getAuditService(realm);
        }
    });
}
Also used : RealmContext(org.forgerock.openam.rest.RealmContext) Context(org.forgerock.services.context.Context) QueryRequest(org.forgerock.json.resource.QueryRequest) AuditEndpointAuditFilter(org.forgerock.openam.rest.fluent.AuditEndpointAuditFilter) UpdateRequest(org.forgerock.json.resource.UpdateRequest) CreateRequest(org.forgerock.json.resource.CreateRequest) AMAuditService(org.forgerock.openam.audit.AMAuditService) PatchRequest(org.forgerock.json.resource.PatchRequest) Promise(org.forgerock.util.promise.Promise) RequestHandler(org.forgerock.json.resource.RequestHandler) ActionRequest(org.forgerock.json.resource.ActionRequest) RealmContextFilter(org.forgerock.openam.rest.RealmContextFilter) SpecialOrAdminOrAgentAuthzModule(org.forgerock.openam.rest.authz.SpecialOrAdminOrAgentAuthzModule) QueryResourceHandler(org.forgerock.json.resource.QueryResourceHandler) DeleteRequest(org.forgerock.json.resource.DeleteRequest) ReadRequest(org.forgerock.json.resource.ReadRequest)

Example 2 with RealmContext

use of org.forgerock.openam.rest.RealmContext in project OpenAM by OpenRock.

the class AuthenticationServiceV1 method getHttpServletRequest.

/**
     * Gets the HttpServletRequest from Restlet and wraps the HttpServletRequest with the URI realm as long as
     * the request does not contain the realm as a query parameter.
     *
     * @return The HttpServletRequest
     */
private HttpServletRequest getHttpServletRequest(Context context, JsonValue jsonValue) {
    AttributesContext requestContext = context.asContext(AttributesContext.class);
    Map<String, Object> requestAttributes = requestContext.getAttributes();
    final HttpServletRequest request = (HttpServletRequest) requestAttributes.get(HttpServletRequest.class.getName());
    // The request contains the realm query param then use that over any realm parsed from the URI
    final String queryParamRealm = request.getParameter(REALM);
    if (queryParamRealm != null && !queryParamRealm.isEmpty()) {
        RealmContext rc = new RealmContext(context);
        rc.setOverrideRealm(queryParamRealm);
        return wrapRequest(request, rc, jsonValue);
    }
    return wrapRequest(request, context.asContext(RealmContext.class), jsonValue);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AttributesContext(org.forgerock.services.context.AttributesContext) RealmContext(org.forgerock.openam.rest.RealmContext)

Example 3 with RealmContext

use of org.forgerock.openam.rest.RealmContext in project OpenAM by OpenRock.

the class IdentityResourceV2 method actionInstance.

/**
     * {@inheritDoc}
     */
@Override
public Promise<ActionResponse, ResourceException> actionInstance(final Context context, final String resourceId, final ActionRequest request) {
    String action = request.getAction();
    if ("changePassword".equalsIgnoreCase(action)) {
        RealmContext realmContext = context.asContext(RealmContext.class);
        final String realm = realmContext.getResolvedRealm();
        JsonValue value = request.getContent();
        try {
            String userPassword = value.get(USER_PASSWORD).asString();
            if (StringUtils.isBlank(userPassword)) {
                throw new BadRequestException("'" + USER_PASSWORD + "' attribute not set in JSON content.");
            }
            String currentPassword = value.get(CURRENT_PASSWORD).asString();
            if (StringUtils.isBlank(currentPassword)) {
                throw new BadRequestException("'" + CURRENT_PASSWORD + "' attribute not set in JSON content.");
            }
            IdentityRestUtils.changePassword(context, realm, resourceId, currentPassword, userPassword);
            if (debug.messageEnabled()) {
                String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
                debug.message("IdentityResource.actionInstance :: ACTION of change password for " + resourceId + " in realm " + realm + " performed by " + principalName);
            }
            return newResultPromise(newActionResponse(json(object())));
        } catch (ResourceException re) {
            debug.warning("Cannot change password! " + resourceId + ":" + re);
            return re.asPromise();
        }
    } else {
        return new NotSupportedException(action + " not supported for resource instances").asPromise();
    }
}
Also used : RealmContext(org.forgerock.openam.rest.RealmContext) JsonValue(org.forgerock.json.JsonValue) BadRequestException(org.forgerock.json.resource.BadRequestException) ResourceException(org.forgerock.json.resource.ResourceException) NotSupportedException(org.forgerock.json.resource.NotSupportedException)

Example 4 with RealmContext

use of org.forgerock.openam.rest.RealmContext in project OpenAM by OpenRock.

the class IdentityResourceV2 method createInstance.

/**
     * {@inheritDoc}
     */
@Override
public Promise<ResourceResponse, ResourceException> createInstance(final Context context, final CreateRequest request) {
    RealmContext realmContext = context.asContext(RealmContext.class);
    final String realm = realmContext.getResolvedRealm();
    try {
        // anyone can create an account add
        SSOToken admin = getSSOToken(getCookieFromServerContext(context));
        final JsonValue jVal = request.getContent();
        String resourceId = request.getNewResourceId();
        IdentityDetails identity = jsonValueToIdentityDetails(objectType, jVal, realm);
        // check to see if request has included resource ID
        if (resourceId != null) {
            if (identity.getName() != null) {
                if (!resourceId.equalsIgnoreCase(identity.getName())) {
                    ResourceException be = new BadRequestException("id in path does not match id in request body");
                    debug.error("IdentityResource.createInstance() :: Cannot CREATE ", be);
                    return be.asPromise();
                }
            }
            identity.setName(resourceId);
        } else {
            resourceId = identity.getName();
        }
        UserAttributeInfo userAttributeInfo = configHandler.getConfig(realm, UserAttributeInfoBuilder.class);
        enforceWhiteList(context, request.getContent(), objectType, userAttributeInfo.getValidCreationAttributes());
        final String id = resourceId;
        return attemptResourceCreation(realm, admin, identity, resourceId).thenAsync(new AsyncFunction<IdentityDetails, ResourceResponse, ResourceException>() {

            @Override
            public Promise<ResourceResponse, ResourceException> apply(IdentityDetails dtls) {
                if (dtls != null) {
                    String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
                    debug.message("IdentityResource.createInstance :: CREATE of resourceId={} in realm={} " + "performed by principalName={}", id, realm, principalName);
                    ResourceResponse resource = newResourceResponse(id, "0", identityDetailsToJsonValue(dtls));
                    return newResultPromise(resource);
                } else {
                    debug.error("IdentityResource.createInstance() :: Identity not found");
                    return new NotFoundException("Identity not found").asPromise();
                }
            }
        });
    } catch (SSOException e) {
        return new ForbiddenException(e).asPromise();
    } catch (BadRequestException bre) {
        return bre.asPromise();
    }
}
Also used : UserAttributeInfo(org.forgerock.openam.core.rest.UserAttributeInfo) ForbiddenException(org.forgerock.json.resource.ForbiddenException) SSOToken(com.iplanet.sso.SSOToken) RealmContext(org.forgerock.openam.rest.RealmContext) JsonValue(org.forgerock.json.JsonValue) NotFoundException(org.forgerock.json.resource.NotFoundException) ServiceNotFoundException(com.sun.identity.sm.ServiceNotFoundException) SSOException(com.iplanet.sso.SSOException) Promises.newResultPromise(org.forgerock.util.promise.Promises.newResultPromise) Promise(org.forgerock.util.promise.Promise) Responses.newResourceResponse(org.forgerock.json.resource.Responses.newResourceResponse) ResourceResponse(org.forgerock.json.resource.ResourceResponse) IdentityDetails(com.sun.identity.idsvcs.IdentityDetails) BadRequestException(org.forgerock.json.resource.BadRequestException) ResourceException(org.forgerock.json.resource.ResourceException)

Example 5 with RealmContext

use of org.forgerock.openam.rest.RealmContext in project OpenAM by OpenRock.

the class IdentityResourceV1 method readInstance.

/**
     * {@inheritDoc}
     */
@Override
public Promise<ResourceResponse, ResourceException> readInstance(final Context context, final String resourceId, final ReadRequest request) {
    RealmContext realmContext = context.asContext(RealmContext.class);
    final String realm = realmContext.getResolvedRealm();
    IdentityDetails dtls;
    try {
        SSOToken admin = getSSOToken(getCookieFromServerContext(context));
        dtls = identityServices.read(resourceId, getIdentityServicesAttributes(realm), admin);
        String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
        debug.message("IdentityResource.readInstance :: READ of resourceId={} in realm={} performed by " + "principalName={}", resourceId, realm, principalName);
        return newResultPromise(buildResourceResponse(resourceId, context, dtls));
    } catch (final NeedMoreCredentials needMoreCredentials) {
        debug.error("IdentityResource.readInstance() :: Cannot READ resourceId={} : User does not have enough " + "privileges.", resourceId, needMoreCredentials);
        return new ForbiddenException("User does not have enough privileges.", needMoreCredentials).asPromise();
    } catch (final ObjectNotFound objectNotFound) {
        debug.error("IdentityResource.readInstance() :: Cannot READ resourceId={} : Resource cannot be found.", resourceId, objectNotFound);
        return new NotFoundException("Resource cannot be found.", objectNotFound).asPromise();
    } catch (final TokenExpired tokenExpired) {
        debug.error("IdentityResource.readInstance() :: Cannot READ resourceId={} : Unauthorized", resourceId, tokenExpired);
        return new PermanentException(401, "Unauthorized", null).asPromise();
    } catch (final AccessDenied accessDenied) {
        debug.error("IdentityResource.readInstance() :: Cannot READ resourceId={} : Access denied", resourceId, accessDenied);
        return new ForbiddenException(accessDenied.getMessage(), accessDenied).asPromise();
    } catch (final GeneralFailure generalFailure) {
        debug.error("IdentityResource.readInstance() :: Cannot READ resourceId={}", resourceId, generalFailure);
        return new BadRequestException(generalFailure.getMessage(), generalFailure).asPromise();
    } catch (final Exception e) {
        debug.error("IdentityResource.readInstance() :: Cannot READ resourceId={}", resourceId, e);
        return new NotFoundException(e.getMessage(), e).asPromise();
    }
}
Also used : ForbiddenException(org.forgerock.json.resource.ForbiddenException) IdentityRestUtils.getSSOToken(org.forgerock.openam.core.rest.IdentityRestUtils.getSSOToken) SSOToken(com.iplanet.sso.SSOToken) NeedMoreCredentials(com.sun.identity.idsvcs.NeedMoreCredentials) RealmContext(org.forgerock.openam.rest.RealmContext) NotFoundException(org.forgerock.json.resource.NotFoundException) ServiceNotFoundException(com.sun.identity.sm.ServiceNotFoundException) AccessDenied(com.sun.identity.idsvcs.AccessDenied) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) DeleteFailedException(org.forgerock.openam.cts.exceptions.DeleteFailedException) SSOException(com.iplanet.sso.SSOException) NotFoundException(org.forgerock.json.resource.NotFoundException) NotSupportedException(org.forgerock.json.resource.NotSupportedException) BadRequestException(org.forgerock.json.resource.BadRequestException) MessagingException(javax.mail.MessagingException) ConflictException(org.forgerock.json.resource.ConflictException) PermanentException(org.forgerock.json.resource.PermanentException) ForbiddenException(org.forgerock.json.resource.ForbiddenException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ServiceNotFoundException(com.sun.identity.sm.ServiceNotFoundException) IdRepoException(com.sun.identity.idm.IdRepoException) SMSException(com.sun.identity.sm.SMSException) ResourceException(org.forgerock.json.resource.ResourceException) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) ObjectNotFound(com.sun.identity.idsvcs.ObjectNotFound) PermanentException(org.forgerock.json.resource.PermanentException) GeneralFailure(com.sun.identity.idsvcs.GeneralFailure) IdentityRestUtils.jsonValueToIdentityDetails(org.forgerock.openam.core.rest.IdentityRestUtils.jsonValueToIdentityDetails) IdentityDetails(com.sun.identity.idsvcs.IdentityDetails) BadRequestException(org.forgerock.json.resource.BadRequestException) TokenExpired(com.sun.identity.idsvcs.TokenExpired)

Aggregations

RealmContext (org.forgerock.openam.rest.RealmContext)94 ResourceException (org.forgerock.json.resource.ResourceException)63 ResourceResponse (org.forgerock.json.resource.ResourceResponse)58 Context (org.forgerock.services.context.Context)53 Test (org.testng.annotations.Test)53 Subject (javax.security.auth.Subject)42 ClientContext (org.forgerock.services.context.ClientContext)41 SSOTokenContext (org.forgerock.openam.rest.resource.SSOTokenContext)40 JsonValue (org.forgerock.json.JsonValue)35 Matchers.anyString (org.mockito.Matchers.anyString)27 SubjectContext (org.forgerock.openam.rest.resource.SubjectContext)20 BadRequestException (org.forgerock.json.resource.BadRequestException)19 SSOException (com.iplanet.sso.SSOException)17 Application (com.sun.identity.entitlement.Application)16 ForbiddenException (org.forgerock.json.resource.ForbiddenException)16 NotFoundException (org.forgerock.json.resource.NotFoundException)15 PermanentException (org.forgerock.json.resource.PermanentException)15 QueryResourceHandler (org.forgerock.json.resource.QueryResourceHandler)15 ReadRequest (org.forgerock.json.resource.ReadRequest)15 SSOToken (com.iplanet.sso.SSOToken)14