Search in sources :

Example 1 with MidPointPrincipal

use of com.evolveum.midpoint.security.api.MidPointPrincipal in project midpoint by Evolveum.

the class PageTaskAdd method createTask.

private TaskType createTask(TaskAddDto dto) throws SchemaException {
    TaskType task = new TaskType();
    MidPointPrincipal owner = SecurityUtils.getPrincipalUser();
    ObjectReferenceType ownerRef = new ObjectReferenceType();
    ownerRef.setOid(owner.getOid());
    ownerRef.setType(owner.getUser().COMPLEX_TYPE);
    task.setOwnerRef(ownerRef);
    task.setCategory(dto.getCategory());
    String handlerUri = getTaskManager().getHandlerUriForCategory(dto.getCategory());
    if (handlerUri == null) {
        throw new SystemException("Cannot determine task handler URI for category " + dto.getCategory());
    }
    task.setHandlerUri(handlerUri);
    ObjectReferenceType objectRef;
    if (dto.getResource() != null) {
        objectRef = new ObjectReferenceType();
        objectRef.setOid(dto.getResource().getOid());
        objectRef.setType(ResourceType.COMPLEX_TYPE);
        task.setObjectRef(objectRef);
    }
    task.setName(WebComponentUtil.createPolyFromOrigString(dto.getName()));
    task.setRecurrence(dto.getReccuring() ? TaskRecurrenceType.RECURRING : TaskRecurrenceType.SINGLE);
    task.setBinding(dto.getBound() ? TaskBindingType.TIGHT : TaskBindingType.LOOSE);
    ScheduleType schedule = new ScheduleType();
    schedule.setInterval(dto.getInterval());
    schedule.setCronLikePattern(dto.getCron());
    schedule.setEarliestStartTime(MiscUtil.asXMLGregorianCalendar(dto.getNotStartBefore()));
    schedule.setLatestStartTime(MiscUtil.asXMLGregorianCalendar(dto.getNotStartAfter()));
    schedule.setMisfireAction(dto.getMisfireAction());
    task.setSchedule(schedule);
    if (dto.getSuspendedState()) {
        task.setExecutionStatus(TaskExecutionStatusType.SUSPENDED);
    } else {
        task.setExecutionStatus(TaskExecutionStatusType.RUNNABLE);
    }
    if (dto.getThreadStop() != null) {
        task.setThreadStopAction(dto.getThreadStop());
    } else {
        // fill-in default
        if (dto.getRunUntilNodeDown() == true) {
            task.setThreadStopAction(ThreadStopActionType.CLOSE);
        } else {
            task.setThreadStopAction(ThreadStopActionType.RESTART);
        }
    }
    if (dto.isDryRun()) {
        PrismObject<TaskType> prismTask = task.asPrismObject();
        ItemPath path = new ItemPath(TaskType.F_EXTENSION, SchemaConstants.MODEL_EXTENSION_DRY_RUN);
        PrismProperty dryRun = prismTask.findOrCreateProperty(path);
        SchemaRegistry registry = getPrismContext().getSchemaRegistry();
        PrismPropertyDefinition def = registry.findPropertyDefinitionByElementName(SchemaConstants.MODEL_EXTENSION_DRY_RUN);
        dryRun.setDefinition(def);
        dryRun.setRealValue(true);
    }
    if (dto.getFocusType() != null) {
        PrismObject<TaskType> prismTask = task.asPrismObject();
        ItemPath path = new ItemPath(TaskType.F_EXTENSION, SchemaConstants.MODEL_EXTENSION_OBJECT_TYPE);
        PrismProperty focusType = prismTask.findOrCreateProperty(path);
        focusType.setRealValue(dto.getFocusType());
    }
    if (dto.getKind() != null) {
        PrismObject<TaskType> prismTask = task.asPrismObject();
        ItemPath path = new ItemPath(TaskType.F_EXTENSION, SchemaConstants.MODEL_EXTENSION_KIND);
        PrismProperty kind = prismTask.findOrCreateProperty(path);
        SchemaRegistry registry = getPrismContext().getSchemaRegistry();
        PrismPropertyDefinition def = registry.findPropertyDefinitionByElementName(SchemaConstants.MODEL_EXTENSION_KIND);
        kind.setDefinition(def);
        kind.setRealValue(dto.getKind());
    }
    if (dto.getIntent() != null && StringUtils.isNotEmpty(dto.getIntent())) {
        PrismObject<TaskType> prismTask = task.asPrismObject();
        ItemPath path = new ItemPath(TaskType.F_EXTENSION, SchemaConstants.MODEL_EXTENSION_INTENT);
        PrismProperty intent = prismTask.findOrCreateProperty(path);
        SchemaRegistry registry = getPrismContext().getSchemaRegistry();
        PrismPropertyDefinition def = registry.findPropertyDefinitionByElementName(SchemaConstants.MODEL_EXTENSION_INTENT);
        intent.setDefinition(def);
        intent.setRealValue(dto.getIntent());
    }
    if (dto.getObjectClass() != null && StringUtils.isNotEmpty(dto.getObjectClass())) {
        PrismObject<TaskType> prismTask = task.asPrismObject();
        ItemPath path = new ItemPath(TaskType.F_EXTENSION, SchemaConstants.OBJECTCLASS_PROPERTY_NAME);
        PrismProperty objectClassProperty = prismTask.findOrCreateProperty(path);
        QName objectClass = null;
        for (QName q : model.getObject().getObjectClassList()) {
            if (q.getLocalPart().equals(dto.getObjectClass())) {
                objectClass = q;
            }
        }
        SchemaRegistry registry = getPrismContext().getSchemaRegistry();
        PrismPropertyDefinition def = registry.findPropertyDefinitionByElementName(SchemaConstants.OBJECTCLASS_PROPERTY_NAME);
        objectClassProperty.setDefinition(def);
        objectClassProperty.setRealValue(objectClass);
    }
    return task;
}
Also used : ScheduleType(com.evolveum.midpoint.xml.ns._public.common.common_3.ScheduleType) ObjectReferenceType(com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType) PrismProperty(com.evolveum.midpoint.prism.PrismProperty) SystemException(com.evolveum.midpoint.util.exception.SystemException) PrismPropertyDefinition(com.evolveum.midpoint.prism.PrismPropertyDefinition) QName(javax.xml.namespace.QName) TaskType(com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType) SchemaRegistry(com.evolveum.midpoint.prism.schema.SchemaRegistry) MidPointPrincipal(com.evolveum.midpoint.security.api.MidPointPrincipal) ItemPath(com.evolveum.midpoint.prism.path.ItemPath)

Example 2 with MidPointPrincipal

use of com.evolveum.midpoint.security.api.MidPointPrincipal in project midpoint by Evolveum.

the class SpringAuthenticationInjectorInterceptor method handleMessage.

@Override
public void handleMessage(SoapMessage message) throws Fault {
    //Note: in constructor we have specified that we will be called after we have been successfully authenticated the user through WS-Security
    //Now we will only set the Spring Authentication object based on the user found in the header
    LOGGER.trace("Intercepted message: {}", message);
    SOAPMessage saajSoapMessage = securityHelper.getSOAPMessage(message);
    if (saajSoapMessage == null) {
        LOGGER.error("No soap message in handler");
        throw createFault(WSSecurityException.ErrorCode.FAILURE);
    }
    ConnectionEnvironment connEnv = ConnectionEnvironment.create(SchemaConstants.CHANNEL_WEB_SERVICE_URI);
    String username = null;
    try {
        username = securityHelper.getUsernameFromMessage(saajSoapMessage);
        LOGGER.trace("Attempt to authenticate user '{}'", username);
        if (StringUtils.isBlank(username)) {
            message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
            securityHelper.auditLoginFailure(username, null, connEnv, "Empty username");
            throw createFault(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
        }
        MidPointPrincipal principal;
        try {
            principal = userDetailsService.getPrincipal(username);
        } catch (SchemaException e) {
            LOGGER.debug("Access to web service denied for user '{}': schema error: {}", username, e.getMessage(), e);
            message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
            securityHelper.auditLoginFailure(username, null, connEnv, "Schema error: " + e.getMessage());
            throw new Fault(e);
        }
        LOGGER.trace("Principal: {}", principal);
        if (principal == null) {
            message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
            securityHelper.auditLoginFailure(username, null, connEnv, "No user");
            throw createFault(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
        }
        // Account validity and credentials and all this stuff should be already checked
        // in the password callback
        Authentication authentication = new UsernamePasswordAuthenticationToken(principal, null);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        String operationName;
        try {
            operationName = DOMUtil.getFirstChildElement(saajSoapMessage.getSOAPBody()).getLocalName();
        } catch (SOAPException e) {
            LOGGER.debug("Access to web service denied for user '{}': SOAP error: {}", username, e.getMessage(), e);
            message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
            securityHelper.auditLoginFailure(username, principal.getUser(), connEnv, "SOAP error: " + e.getMessage());
            throw new Fault(e);
        }
        // AUTHORIZATION
        boolean isAuthorized;
        try {
            isAuthorized = securityEnforcer.isAuthorized(AuthorizationConstants.AUTZ_WS_ALL_URL, AuthorizationPhaseType.REQUEST, null, null, null, null);
            LOGGER.trace("Determined authorization for web service access (action: {}): {}", AuthorizationConstants.AUTZ_WS_ALL_URL, isAuthorized);
        } catch (SchemaException e) {
            LOGGER.debug("Access to web service denied for user '{}': schema error: {}", username, e.getMessage(), e);
            message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
            securityHelper.auditLoginFailure(username, principal.getUser(), connEnv, "Schema error: " + e.getMessage());
            throw createFault(WSSecurityException.ErrorCode.FAILURE);
        }
        if (!isAuthorized) {
            String action = QNameUtil.qNameToUri(new QName(AuthorizationConstants.NS_AUTHORIZATION_WS, operationName));
            try {
                isAuthorized = securityEnforcer.isAuthorized(action, AuthorizationPhaseType.REQUEST, null, null, null, null);
                LOGGER.trace("Determined authorization for web service operation {} (action: {}): {}", operationName, action, isAuthorized);
            } catch (SchemaException e) {
                LOGGER.debug("Access to web service denied for user '{}': schema error: {}", username, e.getMessage(), e);
                message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
                securityHelper.auditLoginFailure(username, principal.getUser(), connEnv, "Schema error: " + e.getMessage());
                throw createFault(WSSecurityException.ErrorCode.FAILURE);
            }
        }
        if (!isAuthorized) {
            LOGGER.debug("Access to web service denied for user '{}': not authorized", username);
            message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
            securityHelper.auditLoginFailure(username, principal.getUser(), connEnv, "Not authorized");
            throw createFault(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
        }
    } catch (WSSecurityException e) {
        LOGGER.debug("Access to web service denied for user '{}': security exception: {}", username, e.getMessage(), e);
        message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
        securityHelper.auditLoginFailure(username, null, connEnv, "Security exception: " + e.getMessage());
        throw new Fault(e, e.getFaultCode());
    } catch (ObjectNotFoundException e) {
        LOGGER.debug("Access to web service denied for user '{}': object not found: {}", username, e.getMessage(), e);
        message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
        securityHelper.auditLoginFailure(username, null, connEnv, "No user");
        throw createFault(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
    }
    // Avoid auditing login attempt again if the operation fails on internal authorization
    message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
    LOGGER.debug("Access to web service allowed for user '{}'", username);
}
Also used : SchemaException(com.evolveum.midpoint.util.exception.SchemaException) QName(javax.xml.namespace.QName) Fault(org.apache.cxf.interceptor.Fault) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) SOAPMessage(javax.xml.soap.SOAPMessage) ConnectionEnvironment(com.evolveum.midpoint.security.api.ConnectionEnvironment) Authentication(org.springframework.security.core.Authentication) SOAPException(javax.xml.soap.SOAPException) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) MidPointPrincipal(com.evolveum.midpoint.security.api.MidPointPrincipal)

Example 3 with MidPointPrincipal

use of com.evolveum.midpoint.security.api.MidPointPrincipal in project midpoint by Evolveum.

the class WebComponentUtil method createSingleRecurrenceTask.

public static TaskType createSingleRecurrenceTask(String taskName, QName applicableType, ObjectQuery query, ObjectDelta delta, ModelExecuteOptions options, String category, PageBase pageBase) throws SchemaException {
    TaskType task = new TaskType();
    MidPointPrincipal owner = SecurityUtils.getPrincipalUser();
    ObjectReferenceType ownerRef = new ObjectReferenceType();
    ownerRef.setOid(owner.getOid());
    ownerRef.setType(owner.getUser().COMPLEX_TYPE);
    task.setOwnerRef(ownerRef);
    task.setBinding(TaskBindingType.LOOSE);
    task.setCategory(category);
    task.setExecutionStatus(TaskExecutionStatusType.RUNNABLE);
    task.setRecurrence(TaskRecurrenceType.SINGLE);
    task.setThreadStopAction(ThreadStopActionType.RESTART);
    task.setHandlerUri(pageBase.getTaskService().getHandlerUriForCategory(category));
    ScheduleType schedule = new ScheduleType();
    schedule.setMisfireAction(MisfireActionType.EXECUTE_IMMEDIATELY);
    task.setSchedule(schedule);
    task.setName(WebComponentUtil.createPolyFromOrigString(taskName));
    PrismObject<TaskType> prismTask = task.asPrismObject();
    ItemPath path = new ItemPath(TaskType.F_EXTENSION, SchemaConstants.MODEL_EXTENSION_OBJECT_QUERY);
    PrismProperty objectQuery = prismTask.findOrCreateProperty(path);
    QueryType queryType = QueryJaxbConvertor.createQueryType(query, pageBase.getPrismContext());
    objectQuery.addRealValue(queryType);
    path = new ItemPath(TaskType.F_EXTENSION, SchemaConstants.MODEL_EXTENSION_OBJECT_TYPE);
    PrismProperty objectType = prismTask.findOrCreateProperty(path);
    objectType.setRealValue(applicableType);
    if (delta != null) {
        path = new ItemPath(TaskType.F_EXTENSION, SchemaConstants.MODEL_EXTENSION_OBJECT_DELTA);
        PrismProperty objectDelta = prismTask.findOrCreateProperty(path);
        objectDelta.setRealValue(DeltaConvertor.toObjectDeltaType(delta));
    }
    if (options != null) {
        prismTask.findOrCreateProperty(new ItemPath(TaskType.F_EXTENSION, SchemaConstants.MODEL_EXTENSION_EXECUTE_OPTIONS)).setRealValue(options.toModelExecutionOptionsType());
    }
    return task;
}
Also used : PrismProperty(com.evolveum.midpoint.prism.PrismProperty) QueryType(com.evolveum.prism.xml.ns._public.query_3.QueryType) MidPointPrincipal(com.evolveum.midpoint.security.api.MidPointPrincipal) ItemPath(com.evolveum.midpoint.prism.path.ItemPath)

Example 4 with MidPointPrincipal

use of com.evolveum.midpoint.security.api.MidPointPrincipal in project midpoint by Evolveum.

the class PageWorkItem method initButtons.

private void initButtons(Form mainForm) {
    VisibleBehaviour isAllowedToSubmit = new VisibleBehaviour(() -> getWorkflowManager().isCurrentUserAuthorizedToSubmit(workItemDtoModel.getObject().getWorkItem()));
    VisibleBehaviour isAllowedToDelegate = new VisibleBehaviour(() -> getWorkflowManager().isCurrentUserAuthorizedToDelegate(workItemDtoModel.getObject().getWorkItem()));
    VisibleBehaviour isAllowedToClaim = new VisibleBehaviour(() -> workItemDtoModel.getObject().getWorkItem().getAssigneeRef() == null && getWorkflowManager().isCurrentUserAuthorizedToClaim(workItemDtoModel.getObject().getWorkItem()));
    VisibleBehaviour isAllowedToRelease = new VisibleBehaviour(() -> {
        WorkItemType workItem = workItemDtoModel.getObject().getWorkItem();
        MidPointPrincipal principal;
        try {
            principal = (MidPointPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        } catch (ClassCastException e) {
            return false;
        }
        String principalOid = principal.getOid();
        return workItem.getAssigneeRef() != null && workItem.getAssigneeRef().stream().anyMatch(ref -> ref.getOid().equals(principalOid)) && (!workItem.getCandidateRef().isEmpty());
    });
    AjaxSubmitButton claim = new DefaultAjaxSubmitButton(ID_CLAIM, createStringResource("pageWorkItem.button.claim"), this, (target, form) -> claimPerformed(target));
    claim.add(isAllowedToClaim);
    mainForm.add(claim);
    AjaxSubmitButton release = new DefaultAjaxSubmitButton(ID_RELEASE, createStringResource("pageWorkItem.button.release"), this, (target, form) -> releasePerformed(target));
    release.add(isAllowedToRelease);
    mainForm.add(release);
    AjaxSubmitButton approve = new DefaultAjaxSubmitButton(ID_APPROVE, createStringResource("pageWorkItem.button.approve"), this, (target, form) -> savePerformed(target, true));
    approve.add(isAllowedToSubmit);
    mainForm.add(approve);
    AjaxSubmitButton reject = new DefaultAjaxSubmitButton(ID_REJECT, createStringResource("pageWorkItem.button.reject"), this, (target, form) -> savePerformed(target, false));
    reject.add(isAllowedToSubmit);
    mainForm.add(reject);
    AjaxSubmitButton delegate = new DefaultAjaxSubmitButton(ID_DELEGATE, createStringResource("pageWorkItem.button.delegate"), this, (target, form) -> delegatePerformed(target));
    delegate.add(isAllowedToDelegate);
    mainForm.add(delegate);
    AjaxButton cancel = new DefaultAjaxButton(ID_CANCEL, createStringResource("pageWorkItem.button.cancel"), this::cancelPerformed);
    mainForm.add(cancel);
}
Also used : DefaultAjaxSubmitButton(com.evolveum.midpoint.web.component.DefaultAjaxSubmitButton) AjaxSubmitButton(com.evolveum.midpoint.web.component.AjaxSubmitButton) DefaultAjaxButton(com.evolveum.midpoint.web.component.DefaultAjaxButton) AjaxButton(com.evolveum.midpoint.web.component.AjaxButton) VisibleBehaviour(com.evolveum.midpoint.web.component.util.VisibleBehaviour) DefaultAjaxButton(com.evolveum.midpoint.web.component.DefaultAjaxButton) DefaultAjaxSubmitButton(com.evolveum.midpoint.web.component.DefaultAjaxSubmitButton) MidPointPrincipal(com.evolveum.midpoint.security.api.MidPointPrincipal)

Example 5 with MidPointPrincipal

use of com.evolveum.midpoint.security.api.MidPointPrincipal in project midpoint by Evolveum.

the class UserMenuPanel method loadModel.

private PasswordQuestionsDto loadModel(PageBase parentPage) {
    LOGGER.trace("Loading user for Security Question Page.");
    PasswordQuestionsDto dto = new PasswordQuestionsDto();
    OperationResult result = new OperationResult(OPERATION_LOAD_USER);
    if (parentPage == null) {
        parentPage = ((PageBase) getPage());
    }
    try {
        MidPointPrincipal principal = SecurityUtils.getPrincipalUser();
        if (principal == null) {
            result.recordNotApplicableIfUnknown();
            return null;
        }
        String userOid = principal.getOid();
        Task task = parentPage.createSimpleTask(OPERATION_LOAD_USER);
        OperationResult subResult = result.createSubresult(OPERATION_LOAD_USER);
        Collection options = SelectorOptions.createCollection(UserType.F_JPEG_PHOTO, GetOperationOptions.createRetrieve(RetrieveOption.INCLUDE));
        PrismObject<UserType> user = parentPage.getModelService().getObject(UserType.class, userOid, options, task, subResult);
        userModel.setObject(user);
        jpegPhoto = user == null ? null : (user.asObjectable() == null ? null : user.asObjectable().getJpegPhoto());
        dto.setSecurityAnswers(createUsersSecurityQuestionsList(user));
        subResult.recordSuccessIfUnknown();
    } catch (Exception ex) {
        LoggingUtils.logExceptionOnDebugLevel(LOGGER, "Couldn't get user Questions, Probably not set yet", ex);
    } finally {
        result.recomputeStatus();
        isUserModelLoaded = true;
    }
    return dto;
}
Also used : Task(com.evolveum.midpoint.task.api.Task) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) PageBase(com.evolveum.midpoint.gui.api.page.PageBase) PasswordQuestionsDto(com.evolveum.midpoint.web.page.admin.home.dto.PasswordQuestionsDto) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException) MidPointPrincipal(com.evolveum.midpoint.security.api.MidPointPrincipal)

Aggregations

MidPointPrincipal (com.evolveum.midpoint.security.api.MidPointPrincipal)75 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)35 Task (com.evolveum.midpoint.task.api.Task)35 Test (org.testng.annotations.Test)30 AbstractInitializedModelIntegrationTest (com.evolveum.midpoint.model.intest.AbstractInitializedModelIntegrationTest)18 TestTriggerTask (com.evolveum.midpoint.model.intest.TestTriggerTask)18 ObjectNotFoundException (com.evolveum.midpoint.util.exception.ObjectNotFoundException)11 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)10 SecurityViolationException (com.evolveum.midpoint.util.exception.SecurityViolationException)10 ItemPath (com.evolveum.midpoint.prism.path.ItemPath)9 UserType (com.evolveum.midpoint.xml.ns._public.common.common_3.UserType)8 IdItemPathSegment (com.evolveum.midpoint.prism.path.IdItemPathSegment)6 NameItemPathSegment (com.evolveum.midpoint.prism.path.NameItemPathSegment)6 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)6 Authentication (org.springframework.security.core.Authentication)6 TestRbac (com.evolveum.midpoint.model.intest.rbac.TestRbac)5 SystemException (com.evolveum.midpoint.util.exception.SystemException)5 Authorization (com.evolveum.midpoint.security.api.Authorization)3 ConnectionEnvironment (com.evolveum.midpoint.security.api.ConnectionEnvironment)3 CommunicationException (com.evolveum.midpoint.util.exception.CommunicationException)3