Search in sources :

Example 16 with AuthorizationException

use of org.apache.shiro.authz.AuthorizationException in project graylog2-server by Graylog2.

the class ShiroAuthorizationFilter method filter.

@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    final SecurityContext securityContext = requestContext.getSecurityContext();
    if (securityContext instanceof ShiroSecurityContext) {
        final ShiroSecurityContext context = (ShiroSecurityContext) securityContext;
        final String userId = RestTools.getUserIdFromRequest(requestContext);
        final ContextAwarePermissionAnnotationHandler annotationHandler = new ContextAwarePermissionAnnotationHandler(context);
        final String[] requiredPermissions = annotation.value();
        try {
            LOG.debug("Checking authorization for user [{}], needs permissions: {}", userId, requiredPermissions);
            annotationHandler.assertAuthorized(annotation);
        } catch (AuthorizationException e) {
            LOG.info("Not authorized. User <{}> is missing permissions {} to perform <{} {}>", userId, Arrays.toString(requiredPermissions), requestContext.getMethod(), requestContext.getUriInfo().getPath());
            throw new ForbiddenException("Not authorized");
        }
    } else {
        throw new ForbiddenException();
    }
}
Also used : ForbiddenException(javax.ws.rs.ForbiddenException) AuthorizationException(org.apache.shiro.authz.AuthorizationException) SecurityContext(javax.ws.rs.core.SecurityContext)

Example 17 with AuthorizationException

use of org.apache.shiro.authz.AuthorizationException in project ddf by codice.

the class AbstractAuthorizingRealm method doGetAuthorizationInfo.

/**
 * Takes the security attributes about the subject of the incoming security token and builds sets
 * of permissions and roles for use in further checking.
 *
 * @param principalCollection holds the security assertions for the primary principal of this
 *     request
 * @return a new collection of permissions and roles corresponding to the security assertions
 * @throws AuthorizationException if there are no security assertions associated with this
 *     principal collection or if the token cannot be processed successfully.
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    LOGGER.debug("Retrieving authorization info for {}", principalCollection.getPrimaryPrincipal());
    Collection<SecurityAssertion> assertions = principalCollection.byType(SecurityAssertion.class);
    if (assertions.isEmpty()) {
        String msg = "No assertion found, cannot retrieve authorization info.";
        throw new AuthorizationException(msg);
    }
    List<AttributeStatement> attributeStatements = assertions.stream().map(SecurityAssertion::getAttributeStatements).flatMap(List::stream).collect(Collectors.toList());
    Set<Permission> permissions = new HashSet<>();
    Set<String> roles = new HashSet<>();
    Map<String, Set<String>> permissionsMap = new HashMap<>();
    Collection<Expansion> expansionServices = getUserExpansionServices();
    for (AttributeStatement curStatement : attributeStatements) {
        addAttributesToMap(curStatement.getAttributes(), permissionsMap, expansionServices);
    }
    for (Map.Entry<String, Set<String>> entry : permissionsMap.entrySet()) {
        permissions.add(new KeyValuePermissionImpl(entry.getKey(), entry.getValue()));
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Adding permission: {} : {}", entry.getKey(), StringUtils.join(entry.getValue(), ","));
        }
    }
    if (permissionsMap.containsKey(SAML_ROLE)) {
        roles.addAll(permissionsMap.get(SAML_ROLE));
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Adding roles to authorization info: {}", StringUtils.join(roles, ","));
        }
    }
    info.setObjectPermissions(permissions);
    info.setRoles(roles);
    return info;
}
Also used : SimpleAuthorizationInfo(org.apache.shiro.authz.SimpleAuthorizationInfo) HashSet(java.util.HashSet) Set(java.util.Set) AuthorizationException(org.apache.shiro.authz.AuthorizationException) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) SecurityAssertion(ddf.security.assertion.SecurityAssertion) AttributeStatement(ddf.security.assertion.AttributeStatement) KeyValuePermissionImpl(ddf.security.permission.impl.KeyValuePermissionImpl) KeyValuePermission(ddf.security.permission.KeyValuePermission) Permission(org.apache.shiro.authz.Permission) KeyValueCollectionPermission(ddf.security.permission.KeyValueCollectionPermission) Expansion(ddf.security.expansion.Expansion) HashMap(java.util.HashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashSet(java.util.HashSet)

Example 18 with AuthorizationException

use of org.apache.shiro.authz.AuthorizationException in project mica2 by obiba.

the class DataAccessRequestResource method archive.

@PUT
@Path("/_archive")
public Response archive(@PathParam("id") String id) {
    if (!SecurityUtils.getSubject().hasRole(Roles.MICA_DAO) && !SecurityUtils.getSubject().hasRole(Roles.MICA_ADMIN)) {
        throw new AuthorizationException();
    }
    DataAccessRequest request = dataAccessRequestService.findById(id);
    if (DataAccessEntityStatus.APPROVED.equals(request.getStatus())) {
        DataAccessRequestTimeline timeline = reportNotificationService.getReportsTimeline(request);
        if (!timeline.hasEndDate())
            throw new BadRequestException("Cannot archive: no data access request end date is defined");
        if (new Date().before(timeline.getEndDate()))
            throw new BadRequestException("Cannot archive: data access request end date not reached");
        request.setArchived(true);
        dataAccessRequestService.archive(request, true);
    } else {
        throw new BadRequestException("Cannot archive: data access request must have been approved before being archived");
    }
    return Response.noContent().build();
}
Also used : DataAccessRequestTimeline(org.obiba.mica.access.domain.DataAccessRequestTimeline) AuthorizationException(org.apache.shiro.authz.AuthorizationException) DataAccessRequest(org.obiba.mica.access.domain.DataAccessRequest) Date(java.util.Date)

Example 19 with AuthorizationException

use of org.apache.shiro.authz.AuthorizationException in project mica2 by obiba.

the class DataAccessRequestResource method changeApplicant.

@PUT
@Path("/_applicant")
public Response changeApplicant(@PathParam("id") String id, @QueryParam("username") String applicant) {
    if (!SecurityUtils.getSubject().hasRole(Roles.MICA_DAO) && !SecurityUtils.getSubject().hasRole(Roles.MICA_ADMIN)) {
        throw new AuthorizationException();
    }
    if (Strings.isNullOrEmpty(applicant))
        throw new IllegalArgumentException("An applicant name is required");
    DataAccessRequest request = dataAccessRequestService.findById(id);
    String originalApplicant = request.getApplicant();
    dataAccessRequestService.changeApplicantAndSave(request, applicant);
    commentsService.findPublicComments("/data-access-request", id).stream().filter(comment -> comment.getCreatedBy().equals(originalApplicant)).map(comment -> Comment.newBuilder(comment).createdBy(applicant).build()).forEach(comment -> commentsService.save(comment, null));
    return Response.noContent().build();
}
Also used : DataAccessForm(org.obiba.mica.micaConfig.domain.DataAccessForm) AbstractDataAccessEntityForm(org.obiba.mica.micaConfig.domain.AbstractDataAccessEntityForm) DataAccessRequestTimeline(org.obiba.mica.access.domain.DataAccessRequestTimeline) Date(java.util.Date) Roles(org.obiba.mica.security.Roles) FileStoreService(org.obiba.mica.file.FileStoreService) TempFile(org.obiba.mica.file.TempFile) Mica(org.obiba.mica.web.model.Mica) Map(java.util.Map) TempFileService(org.obiba.mica.file.service.TempFileService) DataAccessRequestCommentMailNotification(org.obiba.mica.access.notification.DataAccessRequestCommentMailNotification) ParseException(java.text.ParseException) Dtos(org.obiba.mica.web.model.Dtos) CommentsService(org.obiba.mica.core.service.CommentsService) ActionLog(org.obiba.mica.access.domain.ActionLog) SubjectAclService(org.obiba.mica.security.service.SubjectAclService) VariableSetService(org.obiba.mica.dataset.service.VariableSetService) NoSuchCommentException(org.obiba.mica.core.domain.NoSuchCommentException) DataAccessRequestReportNotificationService(org.obiba.mica.access.notification.DataAccessRequestReportNotificationService) Collectors(java.util.stream.Collectors) NoSuchEntityException(org.obiba.mica.NoSuchEntityException) Timed(com.codahale.metrics.annotation.Timed) AuthorizationException(org.apache.shiro.authz.AuthorizationException) NoSuchDataAccessRequestException(org.obiba.mica.access.NoSuchDataAccessRequestException) List(java.util.List) DataAccessEntityStatus(org.obiba.mica.access.domain.DataAccessEntityStatus) javax.ws.rs(javax.ws.rs) Response(javax.ws.rs.core.Response) Optional(java.util.Optional) RequiresAuthentication(org.apache.shiro.authz.annotation.RequiresAuthentication) SecurityUtils(org.apache.shiro.SecurityUtils) Comment(org.obiba.mica.core.domain.Comment) UnauthorizedCommentException(org.obiba.mica.core.domain.UnauthorizedCommentException) DataAccessRequestService(org.obiba.mica.access.service.DataAccessRequestService) DataAccessEntityService(org.obiba.mica.access.service.DataAccessEntityService) EventBus(com.google.common.eventbus.EventBus) Inject(javax.inject.Inject) Strings(com.google.common.base.Strings) DataAccessRequestUtilService(org.obiba.mica.access.service.DataAccessRequestUtilService) ResourceDeletedEvent(org.obiba.mica.security.event.ResourceDeletedEvent) LanguageTag(sun.util.locale.LanguageTag) DataAccessFormService(org.obiba.mica.micaConfig.service.DataAccessFormService) JSONUtils(org.obiba.mica.JSONUtils) DataAccessRequest(org.obiba.mica.access.domain.DataAccessRequest) Attachment(org.obiba.mica.file.Attachment) Logger(org.slf4j.Logger) DateTime(org.joda.time.DateTime) IOException(java.io.IOException) ApplicationContext(org.springframework.context.ApplicationContext) Component(org.springframework.stereotype.Component) DataAccessFeasibilityNotEnabled(org.obiba.mica.micaConfig.DataAccessFeasibilityNotEnabled) DataAccessConfigService(org.obiba.mica.micaConfig.service.DataAccessConfigService) LoggerFactory.getLogger(org.slf4j.LoggerFactory.getLogger) DataAccessAmendmentsNotEnabled(org.obiba.mica.micaConfig.DataAccessAmendmentsNotEnabled) AuthorizationException(org.apache.shiro.authz.AuthorizationException) DataAccessRequest(org.obiba.mica.access.domain.DataAccessRequest)

Example 20 with AuthorizationException

use of org.apache.shiro.authz.AuthorizationException in project mica2 by obiba.

the class DataAccessRequestResource method unarchive.

@DELETE
@Path("/_archive")
public Response unarchive(@PathParam("id") String id) {
    if (!SecurityUtils.getSubject().hasRole(Roles.MICA_ADMIN)) {
        throw new AuthorizationException();
    }
    DataAccessRequest request = dataAccessRequestService.findById(id);
    dataAccessRequestService.archive(request, false);
    return Response.noContent().build();
}
Also used : AuthorizationException(org.apache.shiro.authz.AuthorizationException) DataAccessRequest(org.obiba.mica.access.domain.DataAccessRequest)

Aggregations

AuthorizationException (org.apache.shiro.authz.AuthorizationException)35 IOException (java.io.IOException)10 Map (java.util.Map)7 SimpleAuthorizationInfo (org.apache.shiro.authz.SimpleAuthorizationInfo)7 UnsupportedEncodingException (java.io.UnsupportedEncodingException)6 Response (org.asynchttpclient.Response)6 DataAccessRequest (org.obiba.mica.access.domain.DataAccessRequest)6 List (java.util.List)4 AuthenticationException (org.apache.shiro.authc.AuthenticationException)4 UsernamePasswordToken (org.apache.shiro.authc.UsernamePasswordToken)4 Permission (org.apache.shiro.authz.Permission)4 Subject (org.apache.shiro.subject.Subject)4 Timed (com.codahale.metrics.annotation.Timed)3 ParseException (java.text.ParseException)3 HashSet (java.util.HashSet)3 TimeoutException (java.util.concurrent.TimeoutException)3 AuthenticationToken (org.apache.shiro.authc.AuthenticationToken)3 PrincipalCollection (org.apache.shiro.subject.PrincipalCollection)3 BoundRequestBuilder (org.asynchttpclient.BoundRequestBuilder)3 Test (org.junit.Test)3