Java 类javax.annotation.security.RolesAllowed 实例源码

项目:microprofile-jwt-auth    文件:JsonValuejectionEndpoint.java   
@GET
@Path("/verifyInjectedIssuer")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("Tester")
public JsonObject verifyInjectedIssuer(@QueryParam("iss") String iss) {
    boolean pass = false;
    String msg;
    String issValue = issuer.getString();
    if(issValue == null || issValue.length() == 0) {
        msg = Claims.iss.name()+"value is null or empty, FAIL";
    }
    else if(issValue.equals(iss)) {
        msg = Claims.iss.name()+" PASS";
        pass = true;
    }
    else {
        msg = String.format("%s: %s != %s", Claims.iss.name(), issValue, iss);
    }
    JsonObject result = Json.createObjectBuilder()
        .add("pass", pass)
        .add("msg", msg)
        .build();
    return result;
}
项目:bouncr    文件:OidcProviderController.java   
@Transactional
@RolesAllowed("CREATE_OIDC_PROVIDER")
public HttpResponse create(OidcProviderForm form) {
    if (form.hasErrors()) {
        return templateEngine.render("admin/oidcProvider/new",
                "oidcProvider", form,
                "responseTypes", ResponseType.values(),
                "tokenEndpointAuthMethods", TokenEndpointAuthMethod.values());
    } else {
        OidcProviderDao oidcProviderDao = daoProvider.getDao(OidcProviderDao.class);
        OidcProvider oidcProvider = beansConverter.createFrom(form, OidcProvider.class);
        oidcProviderDao.insert(oidcProvider);

        return UrlRewriter.redirect(OidcProviderController.class, "list", SEE_OTHER);
    }
}
项目:oscm    文件:SubscriptionServiceBean.java   
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER" })
public List<VORoleDefinition> getServiceRolesForService(VOService service)
        throws ObjectNotFoundException, OperationNotPermittedException {

    ArgumentValidator.notNull("service", service);

    Product prod = dataManager.getReference(Product.class,
            service.getKey());
    LocalizerFacade facade = new LocalizerFacade(localizer,
            dataManager.getCurrentUser().getLocale());
    List<RoleDefinition> roleDefinitions = prod.getTechnicalProduct()
            .getRoleDefinitions();

    return RoleAssembler.toVORoleDefinitions(roleDefinitions, facade);
}
项目:oscm    文件:PricingServiceBean.java   
@Override
@RolesAllowed({ "SERVICE_MANAGER", "BROKER_MANAGER", "RESELLER_MANAGER",
        "MARKETPLACE_OWNER", "PLATFORM_OPERATOR" })
public Response getPartnerRevenueSharesForMarketplace(String marketplaceId)
        throws ObjectNotFoundException {

    Response response = new Response();
    try {
        ArgumentValidator.notEmptyString("marketplaceId", marketplaceId);

        Marketplace marketplace = mpServiceLocal
                .getMarketplace(marketplaceId);

        response.getResults().add(toPOPartnerPriceModel(marketplace));
    } finally {

    }
    return response;
}
项目:microprofile-jwt-auth    文件:JsonValuejectionEndpoint.java   
@GET
@Path("/verifyInjectedAudience")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("Tester")
public JsonObject verifyInjectedAudience(@QueryParam("aud") String audience) {
    boolean pass = false;
    String msg;
    // aud
    List<JsonString> audValue = aud.getValuesAs(JsonString.class);
    if(audValue == null || audValue.size() == 0) {
        msg = Claims.aud.name()+"value is null or empty, FAIL";
    }
    else if(audValue.get(0).getString().equals(audience)) {
        msg = Claims.aud.name()+" PASS";
        pass = true;
    }
    else {
        msg = String.format("%s: %s != %s", Claims.aud.name(), audValue, audience);
    }
    JsonObject result = Json.createObjectBuilder()
        .add("pass", pass)
        .add("msg", msg)
        .build();
    return result;
}
项目:oscm    文件:ResaleServiceBean.java   
@RolesAllowed({ "BROKER_MANAGER", "RESELLER_MANAGER" })
public Response getServicesForVendor() {

    Response response = new Response();

    List<Product> productList = spPartnerServiceLocal
            .getProductsForVendor();

    LocalizerFacade facade = new LocalizerFacade(localizer, dm
            .getCurrentUser().getLocale());

    List<VOService> voServicesList = new ArrayList<VOService>();
    for (Product product : productList) {
        voServicesList.add(ProductAssembler.toVOProduct(product, facade));
    }

    response.getResults().add(voServicesList);

    return response;
}
项目:microprofile-jwt-auth    文件:JsonValuejectionEndpoint.java   
@GET
@Path("/verifyInjectedCustomString")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("Tester")
public JsonObject verifyInjectedCustomString(@QueryParam("value") String value) {
    boolean pass = false;
    String msg;
    // iat
    String customValue = customString.getString();
    if(customValue == null || customValue.length() == 0) {
        msg = "customString value is null or empty, FAIL";
    }
    else if(customValue.equals(value)) {
        msg = "customString PASS";
        pass = true;
    }
    else {
        msg = String.format("customString: %s != %s", customValue, value);
    }
    JsonObject result = Json.createObjectBuilder()
        .add("pass", pass)
        .add("msg", msg)
        .build();
    return result;
}
项目:bouncr    文件:GroupController.java   
@RolesAllowed({"MODIFY_GROUP", "MODIFY_ANY_GROUP"})
public HttpResponse edit(Parameters params) {
    GroupDao groupDao = daoProvider.getDao(GroupDao.class);
    Group group = groupDao.selectById(params.getLong("id"));
    GroupForm form = beansConverter.createFrom(group, GroupForm.class);

    UserDao userDao = daoProvider.getDao(UserDao.class);
    List<User> users = userDao.selectAll();

    List<Long> userIds = userDao.selectByGroupId(group.getId())
            .stream()
            .map(User::getId)
            .collect(Collectors.toList());

    return templateEngine.render("admin/group/edit",
            "group", form,
            "users", users,
            "userIds", userIds);
}
项目:oscm    文件:TriggerDefinitionServiceBean.java   
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "PLATFORM_OPERATOR" })
public List<TriggerType> getTriggerTypes() {

    Organization org = this.getOwnOrganization();
    Set<OrganizationRoleType> orgRoles = org.getGrantedRoleTypes();
    Set<TriggerType> triggerTypesSet = new HashSet<TriggerType>();

    if (orgRoles != null) {
        for (OrganizationRoleType orgRole : orgRoles) {
            triggerTypesSet.addAll(getTriggerTypesForRole(orgRole));
        }
    }
    List<TriggerType> triggerTypesList = new ArrayList<TriggerType>();
    triggerTypesList.addAll(triggerTypesSet);
    return triggerTypesList;
}
项目:oscm    文件:PricingServiceBean.java   
@Override
@RolesAllowed("PLATFORM_OPERATOR")
public Response getPartnerServicesWithRevenueShareForTemplate(
        POServiceForPricing service) throws ObjectNotFoundException,
        ServiceOperationException {

    ArgumentValidator.notNull("service", service);
    List<POServicePricing> pricings = new ArrayList<POServicePricing>();
    List<Product> partnerProducts = spPartnerServiceLocal
            .getPartnerProductsForTemplate(service.getKey());
    for (Product partnerProduct : partnerProducts) {
        pricings.add(assembleServicePricing(partnerProduct));
    }

    return new Response(pricings);
}
项目:oscm    文件:PricingServiceBean.java   
@Override
@RolesAllowed({ "SERVICE_MANAGER", "BROKER_MANAGER", "RESELLER_MANAGER",
        "MARKETPLACE_OWNER", "PLATFORM_OPERATOR" })
public Response getPartnerRevenueShareForAllStatesService(
        POServiceForPricing service) throws ObjectNotFoundException,
        OperationNotPermittedException, ServiceOperationException,
        ServiceStateException {

    ArgumentValidator.notNull("service", service);

    Map<RevenueShareModelType, RevenueShareModel> revenueShareModels = spPartnerServiceLocal
            .getRevenueShareModelsForProduct(service.getKey(),
                    STATUS_CHECK_NOT_NEEDED);

    Response response = getRevenueShareModels(revenueShareModels);

    return response;

}
项目:oscm    文件:ExportBillingDataServiceBean.java   
@Override
@RolesAllowed({ "SERVICE_MANAGER", "RESELLER_MANAGER" })
public Response exportBillingData(POBillingDataExport exportParam)
        throws NoBilingSharesDataAvailableException,
        OrganizationAuthoritiesException {
    ArgumentValidator.notNull("exportParam", exportParam);
    ArgumentValidator.notNull("from", exportParam.getFrom());
    ArgumentValidator.notNull("to", exportParam.getTo());

    Long from = DateConverter
            .getBeginningOfDayInCurrentTimeZone(exportParam.getFrom());
    Long to = DateConverter
            .getBeginningOfNextDayInCurrentTimeZone(exportParam.getTo());

    byte[] xmlResult = null;
    xmlResult = billingService.getCustomerBillingData(from, to,
            exportParam.getOrganizationIds());
    if (xmlResult == null || xmlResult.length < 1) {
        throw new NoBilingSharesDataAvailableException();
    }

    return new Response(xmlResult);
}
项目:oscm    文件:OperatorServiceBean.java   
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER",
        "UNIT_ADMINISTRATOR" })
public List<VOUserDetails> getUnassignedUsersByOrg(Long subscriptionKey,
        Long organizationKey) {
    Query query = dm.createNativeQuery(
            "select distinct usr.tkey, usr.userid, usr.firstname, usr.lastname from  PlatformUser as usr "
                    + " where not exists (select 1 from UsageLicense as lic1 where lic1.subscription_tkey=:subscriptionKey and lic1.user_tkey=usr.tkey) and usr.organizationkey=:organizationKey");

    query.setParameter("subscriptionKey", subscriptionKey);
    query.setParameter("organizationKey", organizationKey);
    List<VOUserDetails> result = new ArrayList<>();
    List<Object[]> resultList = query.getResultList();
    VOUserDetails pu;
    for (Object[] cols : resultList) {
        pu = new VOUserDetails();
        pu.setKey(((BigInteger) cols[TKEY_INDEX]).longValue());
        pu.setUserId((String) cols[ID_INDEX]);
        pu.setFirstName((String) cols[FIRST_NAME_INDEX]);
        pu.setLastName((String) cols[LAST_NAME_INDEX]);
        result.add(pu);
    }
    return result;
}
项目:oscm    文件:ServiceProvisioningServiceBean.java   
@RolesAllowed({ "SERVICE_MANAGER", "RESELLER_MANAGER", "BROKER_MANAGER" })
public List<VOService> getSuppliedServices(
        PerformanceHint performanceHint) {

    Organization currentUsersOrg = dm.getCurrentUser().getOrganization();
    EnumSet<ServiceType> serviceTypes = getServiceTypesForOrg(
            currentUsersOrg);
    List<Product> productList = getProductsOfSupplier(currentUsersOrg,
            serviceTypes);
    LocalizerFacade facade = new LocalizerFacade(localizer,
            dm.getCurrentUser().getLocale());
    ProductAssembler.prefetchData(productList, facade, performanceHint);
    List<VOService> voList = new ArrayList<>();
    for (Product product : productList) {
        voList.add(ProductAssembler.toVOProduct(product, facade,
                performanceHint));
    }

    return voList;
}
项目:oscm    文件:ServiceProvisioningServiceBean.java   
@Override
@RolesAllowed({ "SERVICE_MANAGER", "RESELLER_MANAGER", "BROKER_MANAGER" })
public VOService activateService(VOService service)
        throws ServiceStateException, ObjectNotFoundException,
        OrganizationAuthoritiesException, OperationNotPermittedException,
        ServiceOperationException, TechnicalServiceNotAliveException,
        ServiceNotPublishedException, OperationPendingException,
        ConcurrentModificationException {

    // Activate service
    ServiceVisibilityCheck visChecker = new ServiceVisibilityCheck(dm);
    VOService voProduct = setActivationState(service, true, null,
            visChecker);

    // Check constraint about visibility
    try {
        visChecker.validate();
    } catch (ServiceOperationException e) {
        sessionCtx.setRollbackOnly();
        throw e;
    }

    return voProduct;
}
项目:oscm    文件:AccountServiceBean.java   
@Override
@RolesAllowed({ "SERVICE_MANAGER", "RESELLER_MANAGER", "BROKER_MANAGER" })
public List<VOOrganization> getMyCustomersOptimization() {
    List<VOOrganization> result = new ArrayList<>();

    PlatformUser user = dm.getCurrentUser();
    Organization seller = user.getOrganization();

    List<Organization> list = getCustomersOptimization(seller);

    for (Organization customer : list) {
        result.add(OrganizationAssembler.toVOOrganization(customer, false,
                null, PerformanceHint.ONLY_FIELDS_FOR_LISTINGS));
    }

    return result;
}
项目:bouncr    文件:RealmController.java   
@Transactional
@RolesAllowed({"MODIFY_REALM", "MODIFY_ANY_REALM"})
public HttpResponse update(RealmForm form) {
    if (form.hasErrors()) {
        return templateEngine.render("admin/realm/new",
                "realm", form);
    } else {
        Realm realm = converter.createFrom(form, Realm.class);
        realm.setWriteProtected(false);
        RealmDao realmDao = daoProvider.getDao(RealmDao.class);
        realmDao.update(realm);

        createAssign(form, realm);

        return UrlRewriter.redirect(RealmController.class,
                "listByApplicationId?applicationId=" + form.getApplicationId(), SEE_OTHER);
    }
}
项目:oscm    文件:SubscriptionServiceBean.java   
/**
 * It returns a list of VOSubscriptionIdAndOrganizations objects, which
 * contain the subscriptionIdentifier and the associated customers of the
 * subscription in form of list.If there are no subscriptions an empty list
 * is returned.
 * 
 * The role of organization as a supplier, a broker or a reseller is needed
 * to execute this method.
 * 
 * @return List<VOSubscriptionIdAndOrganizations>
 */
@Override
@RolesAllowed({ "SERVICE_MANAGER", "BROKER_MANAGER", "RESELLER_MANAGER" })
public List<VOSubscriptionIdAndOrganizations> getCustomerSubscriptions()
        throws OrganizationAuthoritiesException {
    Set<SubscriptionStatus> states = EnumSet.of(SubscriptionStatus.ACTIVE,
            SubscriptionStatus.PENDING);
    LocalizerFacade lf = new LocalizerFacade(localizer,
            dataManager.getCurrentUser().getLocale());

    List<Subscription> queryResultList = getQueryResultListSubIdsAndOrgs(
            states);
    Map<String, VOSubscriptionIdAndOrganizations> mapSubIdsAndOrgs = getSubIdsAndOrgs(
            lf, queryResultList);

    return new ArrayList<>(mapSubIdsAndOrgs.values());
}
项目:oscm    文件:ServiceProvisioningServiceBean.java   
@Override
@RolesAllowed("TECHNOLOGY_MANAGER")
public List<String> getInstanceIdsForSellers(List<String> organizationIds) {

    ArgumentValidator.notNull("organizationIds", organizationIds);

    List<String> result = new ArrayList<>();
    Organization providerOrg = dm.getCurrentUser().getOrganization();

    if (organizationIds.size() > 0) {
        Query query = dm
                .createNamedQuery("Subscription.instanceIdsForSuppliers");
        query.setParameter("providerKey",
                Long.valueOf(providerOrg.getKey()));
        query.setParameter("supplierIds", organizationIds);
        query.setParameter("status", EnumSet.of(SubscriptionStatus.ACTIVE,
                SubscriptionStatus.SUSPENDED));
        List<String> instanceIds = ParameterizedTypes
                .list(query.getResultList(), String.class);
        if (instanceIds != null) {
            result.addAll(instanceIds);
        }
    }

    return result;
}
项目:oscm    文件:SubscriptionServiceBean.java   
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER" })
public boolean validateSubscriptionIdForOrganization(
        String subscriptionId) {
    // load all subscriptions
    List<Subscription> subs = subscriptionListService
            .getSubscriptionsForOrganization(null);

    boolean subscriptionIdAlreadyExists = false;
    for (Subscription sub : subs) {
        if (sub.getSubscriptionId().equals(subscriptionId)) {
            subscriptionIdAlreadyExists = true;
            break;
        }
    }
    return subscriptionIdAlreadyExists;
}
项目:oscm    文件:OperatorServiceBean.java   
@Override
@RolesAllowed("PLATFORM_OPERATOR")
public List<VOUserDetails> getUsers()
        throws OrganizationAuthoritiesException {
    Query query = dm.createQuery(
            "select pu.dataContainer.userId, pu.dataContainer.email,o.dataContainer.name, o.dataContainer.organizationId, pu.dataContainer.status, pu.key from PlatformUser pu left join pu.organization o");

    List<VOUserDetails> result = new ArrayList<>();
    final List resultList = query.getResultList();
    for (Object o : resultList) {
        Object[] row = (Object[]) o;
        final VOUserDetails userDetails = new VOUserDetails();
        userDetails.setUserId((String) row[USERID_INDEX]);
        userDetails.setEMail((String) row[EMAIL_INDEX]);
        userDetails.setOrganizationName((String) row[ORGN_NAME_INDEX]);
        userDetails.setOrganizationId((String) row[ORG_ID_INDEX]);
        userDetails.setStatus((UserAccountStatus) row[STATUS_INDEX]);
        userDetails.setKey((Long) row[TKEY_INDEX_5]);
        result.add(userDetails);
    }
    return result;
}
项目:oscm    文件:BrandServiceBean.java   
@Override
@RolesAllowed({ "MARKETPLACE_OWNER" })
public void saveMessageProperties(Map<String, Properties> propertiesMap,
        String marketplaceId) throws OperationNotPermittedException,
        ObjectNotFoundException {

    ArgumentValidator.notEmptyString("marketplaceId", marketplaceId);

    Organization organization = dm.getCurrentUser().getOrganization();

    Marketplace marketplace = new Marketplace();
    marketplace.setMarketplaceId(marketplaceId);
    marketplace = (Marketplace) dm.getReferenceByBusinessKey(marketplace);

    PermissionCheck.owns(marketplace, organization, logger, null);

    if (propertiesMap != null) {
        for (String localeString : propertiesMap.keySet()) {
            localizer.storeLocalizedResource(localeString,
                    marketplace.getKey(),
                    LocalizedObjectTypes.SHOP_MESSAGE_PROPERTIES,
                    writeProperties(propertiesMap.get(localeString)));
        }
    }

}
项目:oscm    文件:SecurityInvocationHandler.java   
SecurityInvocationHandler(SessionContext sessionContext, Method beanMethod) {
    this.sessionContext = sessionContext;
    RolesAllowed rolesAllowed = beanMethod.getAnnotation(RolesAllowed.class);

    // a somewhat nasty scenario: a bean is spied using Mockito, so the
    // roles allowed annotations have to be retrieved from the superclass...
    Class<?> declaringClass = beanMethod.getDeclaringClass();
    Class<?> superclass = declaringClass.getSuperclass();
    if (declaringClass.getName().contains("Mockito")
            && !superclass.equals(Object.class)) {
        try {
            Method method = superclass.getMethod(beanMethod.getName(),
                    beanMethod.getParameterTypes());
            rolesAllowed = method.getAnnotation(RolesAllowed.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    if (rolesAllowed == null) {
        this.rolesAllowed = new String[0];
    } else {
        this.rolesAllowed = rolesAllowed.value();
    }
}
项目:oscm    文件:UserGroupServiceBean.java   
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "UNIT_ADMINISTRATOR" })
public List<POUserGroupToInvisibleProduct> getInvisibleProducts(
        long userGroupKey) {
    List<UserGroupToInvisibleProduct> invisibleProducts = userGroupService
            .getInvisibleProducts(userGroupKey);
    List<POUserGroupToInvisibleProduct> invisibleProductsPO = new ArrayList<POUserGroupToInvisibleProduct>();
    for (UserGroupToInvisibleProduct userGroupToInvisibleProduct : invisibleProducts) {
        POUserGroupToInvisibleProduct poUserGroupToInvisibleProduct = new POUserGroupToInvisibleProduct();
        poUserGroupToInvisibleProduct.setKey(userGroupToInvisibleProduct
                .getKey());
        poUserGroupToInvisibleProduct
                .setVersion(userGroupToInvisibleProduct.getVersion());
        poUserGroupToInvisibleProduct
                .setForAllUsers(userGroupToInvisibleProduct.isForallusers());
        poUserGroupToInvisibleProduct
                .setServiceKey(userGroupToInvisibleProduct
                        .getProduct_tkey());
        invisibleProductsPO.add(poUserGroupToInvisibleProduct);
    }
    return invisibleProductsPO;
}
项目:bouncr    文件:ApplicationController.java   
@RolesAllowed("CREATE_APPLICATION")
@Transactional
public HttpResponse create(ApplicationForm form) {
    if (form.hasErrors()) {
        return templateEngine.render("admin/application/new",
                "application", form);
    } else {
        Application application = beansConverter.createFrom(form, Application.class);
        application.setWriteProtected(false);
        application.setId(null);
        if (application.getVirtualPath().endsWith("/")) {
            application.setVirtualPath(application.getVirtualPath().replaceFirst("[\\s/]*$", ""));
        }

        ApplicationDao applicationDao = daoProvider.getDao(ApplicationDao.class);
        applicationDao.insert(application);

        return UrlRewriter.redirect(ApplicationController.class, "list", SEE_OTHER);
    }
}
项目:dremio-oss    文件:UserResource.java   
@RolesAllowed("admin")
@DELETE
@Produces(MediaType.APPLICATION_JSON)
public Response deleteUser(@PathParam("userName") UserName userName, @QueryParam("version") Long version) throws IOException, UserNotFoundException {
  if (version == null) {
    throw new ClientErrorException("missing version parameter");
  }

  if (securityContext.getUserPrincipal().getName().equals(userName.getName())) {
    return Response.status(Status.FORBIDDEN).entity(
        new GenericErrorMessage("Deletion of the user account of currently logged in user is not allowed.")).build();
  }

  userService.deleteUser(userName.getName(), version);

  return Response.ok().build();
}
项目:task-app    文件:TaskAppServiceResource.java   
@POST
@Produces(MediaType.TEXT_PLAIN)
@RolesAllowed(value = "TASK_APP_CLIENT")
@Path("/createTask")
public Long createTask(
        @QueryParam("type") String type,
        @QueryParam("name") String name,
        @QueryParam("actor") String actor,
        @QueryParam("creator") String creator) {
    return taskAppService.createTask(type, name, actor, creator);
}
项目:oscm    文件:AccountServiceBean.java   
@Override
@RolesAllowed({ "SERVICE_MANAGER", "RESELLER_MANAGER" })
public Set<VOPaymentType> getDefaultPaymentConfiguration() {

    Organization supplier = dm.getCurrentUser().getOrganization();

    final OrganizationRoleType role;
    if (supplier.getGrantedRoleTypes()
            .contains(OrganizationRoleType.SUPPLIER)) {
        role = OrganizationRoleType.SUPPLIER;
    } else if (supplier.getGrantedRoleTypes()
            .contains(OrganizationRoleType.RESELLER)) {
        role = OrganizationRoleType.RESELLER;
    } else {
        role = null;
    }
    Set<VOPaymentType> result = new HashSet<>();
    List<OrganizationRefToPaymentType> defaultPaymentTypes = supplier
            .getPaymentTypes(true, role,
                    OrganizationRoleType.PLATFORM_OPERATOR.name());
    final LocalizerFacade lf = new LocalizerFacade(localizer,
            dm.getCurrentUser().getLocale());
    for (OrganizationRefToPaymentType orgToPt : defaultPaymentTypes) {
        result.add(PaymentTypeAssembler
                .toVOPaymentType(orgToPt.getPaymentType(), lf));
    }

    return result;
}
项目:holon-vaadin    文件:SecurityAnnotationsViewAccessControl.java   
@Override
public boolean isAccessGranted(UI ui, String beanName) {

    if (applicationContext.findAnnotationOnBean(beanName, DenyAll.class) != null) {
        // DenyAll (no authentication required)
        return false;
    }
    if (applicationContext.findAnnotationOnBean(beanName, PermitAll.class) != null) {
        // PermitAll (no authentication required)
        return true;
    }

    // RolesAllowed - authentication required
    RolesAllowed ra = applicationContext.findAnnotationOnBean(beanName, RolesAllowed.class);
    if (ra != null) {

        // check authentication
        final AuthContext authContext = AuthContext.getCurrent()
                .orElseThrow(() -> new IllegalStateException("No AuthContext available as Context resource: "
                        + "failed to validate RolesAllowed security annotation on View bean name [" + beanName
                        + "]"));
        if (!authContext.getAuthentication().isPresent()) {
            // not authenticated
            return false;
        }

        // check permissions
        if (ra.value().length > 0) {
            // for empty roles names, no role is required, only authentication
            if (!authContext.isPermittedAny(ra.value())) {
                // no roles matches (with ANY semantic)
                return false;
            }
        }
    }

    return true;
}
项目:microprofile-jwt-auth    文件:SubjectEndpoint.java   
@GET
@Path("/getSubjectClass")
@RolesAllowed("Tester")
public String getSubjectClass(@Context SecurityContext sec) throws Exception {
    Subject subject = (Subject) PolicyContext.getContext("javax.security.auth.Subject.container");
    Set<? extends Principal> principalSet = subject.getPrincipals(JsonWebToken.class);
    if (principalSet.size() > 0) {
        return "subject.getPrincipals(JWTPrincipal.class) ok";
    }
    throw new IllegalStateException("subject.getPrincipals(JWTPrincipal.class) == 0");
}
项目:microprofile-jwt-auth    文件:RolesEndpoint.java   
@GET
@Path("/echo")
@RolesAllowed("Echoer")
public String echoInput(@Context SecurityContext sec, @QueryParam("input") String input) {
    Principal user = sec.getUserPrincipal();
    return input + ", user="+user.getName();
}
项目:oscm    文件:SubscriptionServiceBean.java   
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER",
        "UNIT_ADMINISTRATOR" })
public List<VORoleDefinition> getServiceRolesForSubscription(
        String subscriptionId)
        throws ObjectNotFoundException, OperationNotPermittedException {

    ArgumentValidator.notNull("subscriptionId", subscriptionId);

    Subscription sub = manageBean.checkSubscriptionOwner(subscriptionId, 0);

    return getServiceRolesForSubscription(sub);
}
项目:microprofile-jwt-auth    文件:RolesEndpoint.java   
@GET
@Path("/echoNeedsToken2Role")
@RolesAllowed("Token2Role")
public String echoNeedsToken2Role(@Context SecurityContext sec, @QueryParam("input") String input) {
    Principal user = sec.getUserPrincipal();
    return input + ", user="+user.getName();
}
项目:oscm    文件:IdentityServiceBean.java   
@Override
@RolesAllowed("ORGANIZATION_ADMIN")
public void importUsersInOwnOrganization(byte[] csvData,
        String marketplaceId) throws BulkUserImportException,
        ObjectNotFoundException, IllegalArgumentException {

    ArgumentValidator.notNull("csvData", csvData);

    Organization organization = dm.getCurrentUser().getOrganization();

    importUsers(csvData, organization, marketplaceId);
}
项目:microprofile-jwt-auth    文件:RolesEndpoint.java   
/**
 * This endpoint requires a Tester role, and also validates that the caller has the role Echoer by calling
 * {@linkplain SecurityContext#isUserInRole(String)}.
 *
 * @return principal name or FORBIDDEN error
 */
@GET
@Path("/checkIsUserInRole")
@RolesAllowed("Tester")
public Response checkIsUserInRole(@Context SecurityContext sec) {
    Principal user = sec.getUserPrincipal();
    Response response;
    if(!sec.isUserInRole("Echoer")) {
        response = Response.status(new Response.StatusType() {
            @Override
            public int getStatusCode() {
                return Response.Status.FORBIDDEN.getStatusCode();
            }

            @Override
            public Response.Status.Family getFamily() {
                return Response.Status.FORBIDDEN.getFamily();
            }

            @Override
            public String getReasonPhrase() {
                return "SecurityContext.isUserInRole(Echoer) was false";
            }
        }).build();
    }
    else {
        response = Response.ok(user.getName(), MediaType.TEXT_PLAIN).build();
    }
    return response;
}
项目:oscm    文件:UserGroupServiceLocalBean.java   
@RolesAllowed({ "ORGANIZATION_ADMIN" })
public List<UserGroup> getOrganizationalUnits(Pagination pagination) {

    if (pagination != null) {
        return userGroupDao.getUserGroupsForOrganization(pagination);
    }

    return userGroupDao.getUserGroupsForOrganization();
}
项目:oscm    文件:IdentityServiceBean.java   
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "UNIT_ADMINISTRATOR" })
public void revokeUnitRole(VOUser user, UserRoleType role)
        throws ObjectNotFoundException, OperationNotPermittedException {

    ArgumentValidator.notNull("user", user);
    ArgumentValidator.notNull("role", role);
    PlatformUser pUser = getPlatformUser(user.getUserId(),
            dm.getCurrentUser().getTenantId(), true);
    revokeUnitRole(pUser, role);
}
项目:bouncr    文件:UserController.java   
@RolesAllowed({"LIST_USERS", "LIST_ANY_USERS"})
public List<User> search(Parameters params, UserPrincipal principal) {
    String word = params.get("q");
    UserDao userDao = daoProvider.getDao(UserDao.class);
    SelectOptions options = SelectOptions.get();
    return userDao.selectForIncrementalSearch(word, principal, options);
}
项目:coddy    文件:User.java   
@GET
@AuthorizationFilter
@RolesAllowed(Permission.ADMIN)
public List<SimpleUser> getUsers(@DefaultValue("0") @QueryParam("from") final int from,
                                 @DefaultValue("10") @QueryParam("size") final int size) {
    return this.service.getEntity(from, size).stream().map(SimpleUser::new).collect(Collectors.toList());
}
项目:oscm    文件:BillingAdapterDAO.java   
@RolesAllowed({ "PLATFORM_OPERATOR", "TECHNOLOGY_MANAGER",
        "SERVICE_MANAGER" })
public BillingAdapter get(BillingAdapter billingAdapter) {
    BillingAdapter ba = null;
    if (billingAdapter.getKey() != 0L) {
        ba = ds.find(BillingAdapter.class, billingAdapter.getKey());
    } else {
        ba = (BillingAdapter) ds.find(billingAdapter);
    }
    return ba;
}