Example usage for javax.security.auth Subject getPrincipals

List of usage examples for javax.security.auth Subject getPrincipals

Introduction

In this page you can find the example usage for javax.security.auth Subject getPrincipals.

Prototype

public Set<Principal> getPrincipals() 

Source Link

Document

Return the Set of Principals associated with this Subject .

Usage

From source file:org.apache.camel.component.cxf.DefaultCxfBinding.java

/**
 * This method is called by {@link CxfConsumer}.
 *//*from   ww w. j av a 2s . c o m*/
public void populateExchangeFromCxfRequest(org.apache.cxf.message.Exchange cxfExchange,
        Exchange camelExchange) {

    Method method = null;
    QName operationName = null;
    ExchangePattern mep = ExchangePattern.InOut;

    // extract binding operation information
    BindingOperationInfo boi = camelExchange.getProperty(BindingOperationInfo.class.getName(),
            BindingOperationInfo.class);
    if (boi != null) {
        Service service = (Service) cxfExchange.get(Service.class);
        if (service != null) {
            MethodDispatcher md = (MethodDispatcher) service.get(MethodDispatcher.class.getName());
            if (md != null) {
                method = md.getMethod(boi);
            }
        }

        if (boi.getOperationInfo().isOneWay()) {
            mep = ExchangePattern.InOnly;
        }

        operationName = boi.getName();
    }

    // set operation name in header
    if (operationName != null) {
        camelExchange.getIn().setHeader(CxfConstants.OPERATION_NAMESPACE, boi.getName().getNamespaceURI());
        camelExchange.getIn().setHeader(CxfConstants.OPERATION_NAME, boi.getName().getLocalPart());
        if (LOG.isTraceEnabled()) {
            LOG.trace("Set IN header: " + CxfConstants.OPERATION_NAMESPACE + "="
                    + boi.getName().getNamespaceURI());
            LOG.trace("Set IN header: " + CxfConstants.OPERATION_NAME + "=" + boi.getName().getLocalPart());
        }
    } else if (method != null) {
        camelExchange.getIn().setHeader(CxfConstants.OPERATION_NAME, method.getName());
        if (LOG.isTraceEnabled()) {
            LOG.trace("Set IN header: " + CxfConstants.OPERATION_NAME + "=" + method.getName());
        }
    }

    // set message exchange pattern
    camelExchange.setPattern(mep);
    if (LOG.isTraceEnabled()) {
        LOG.trace("Set exchange MEP: " + mep);
    }

    // propagate headers
    Message cxfMessage = cxfExchange.getInMessage();
    propagateHeadersFromCxfToCamel(cxfMessage, camelExchange.getIn(), camelExchange);

    // propagate the security subject from CXF security context
    SecurityContext securityContext = cxfMessage.get(SecurityContext.class);
    if (securityContext != null && securityContext.getUserPrincipal() != null) {
        Subject subject = new Subject();
        subject.getPrincipals().add(securityContext.getUserPrincipal());
        camelExchange.getIn().getHeaders().put(Exchange.AUTHENTICATION, subject);
    }

    // Propagating properties from CXF Exchange to Camel Exchange has an  
    // side effect of copying reply side stuff when the producer is retried.
    // So, we do not want to do this.
    //camelExchange.getProperties().putAll(cxfExchange);

    // propagate request context
    Object value = cxfMessage.get(Client.REQUEST_CONTEXT);
    if (value != null && !headerFilterStrategy.applyFilterToExternalHeaders(Client.REQUEST_CONTEXT, value,
            camelExchange)) {
        camelExchange.getIn().setHeader(Client.REQUEST_CONTEXT, value);
        if (LOG.isTraceEnabled()) {
            LOG.trace("Populate context from CXF message " + Client.REQUEST_CONTEXT + " value=" + value);
        }
    }

    // set body
    Object body = DefaultCxfBinding.getContentFromCxf(cxfMessage,
            camelExchange.getProperty(CxfConstants.DATA_FORMAT_PROPERTY, DataFormat.class));
    if (body != null) {
        camelExchange.getIn().setBody(body);
    }

    // propagate attachments
    if (cxfMessage.getAttachments() != null) {
        for (Attachment attachment : cxfMessage.getAttachments()) {
            camelExchange.getIn().addAttachment(attachment.getId(), attachment.getDataHandler());
        }
    }
}

From source file:org.wso2.andes.server.security.access.config.RuleSet.java

/**
 * Filtered rules list based on a subject and operation.
 *
 * Allows only enabled rules with identity equal to all, the same, or a group with identity as a member,
 * and operation is either all or the same operation.
 *//*from ww  w  . jav a 2  s .  c  om*/
public List<Rule> getRules(final Subject subject, final Operation operation, final ObjectType objectType) {
    final Map<ObjectType, List<Rule>> objects = getObjectToRuleCache(subject, operation);

    // Lookup object type rules for the operation
    if (!objects.containsKey(objectType)) {
        final Set<Principal> principals = subject.getPrincipals();
        boolean controlled = false;
        List<Rule> filtered = new LinkedList<Rule>();
        for (Rule rule : _rules.values()) {
            final Action ruleAction = rule.getAction();
            if (rule.isEnabled()
                    && (ruleAction.getOperation() == Operation.ALL || ruleAction.getOperation() == operation)
                    && (ruleAction.getObjectType() == ObjectType.ALL
                            || ruleAction.getObjectType() == objectType)) {
                controlled = true;

                if (isRelevant(principals, rule)) {
                    filtered.add(rule);
                }
            }
        }

        // Return null if there are no rules at all for this operation and object type
        if (filtered.isEmpty() && controlled == false) {
            filtered = null;
        }

        // Save the rules we selected
        objects.put(objectType, filtered);
    }

    // Return the cached rules
    return objects.get(objectType);
}

From source file:edu.ku.brc.af.auth.specify.SpecifySecurityMgr.java

public void grantPermission(Subject currentSubject, Principal principalToMatchTo, Permission perm) {
    log.debug("grantPermission"); //$NON-NLS-1$
    if (currentSubject == null) {
        log.error("grantPermission - subject is null - cannot grant permission"); //$NON-NLS-1$
        return;/*  w  w w  .j a v a  2  s  .c o  m*/
    }
    if (perm == null) {
        log.error("grantPermission - permission is null - cannot grant permission"); //$NON-NLS-1$
        return;
    }
    Set<Principal> p = currentSubject.getPrincipals();
    if (p == null) {
        log.error(
                "grantPermission - there are no principals associated with this user - cannot grant permission"); //$NON-NLS-1$
        return;
    }

    Iterator<Principal> it = p.iterator();
    while (it.hasNext()) {
        Principal principal = it.next();
        String principalClassName = principal.getClass().getCanonicalName();
        if (principalClassName.equals(SpPrincipal.class.getCanonicalName())) {
            SpPrincipal spp = (SpPrincipal) principal;
            String principalType = spp.getGroupSubClass();
            String principalName = spp.getName();
            SpPrincipal mySpPrincipal = PermissionService.getSpPrincipalByName(principalName);
            if (principalToMatchTo == null) {
                PermissionService.giveSpPrincipalPermission(mySpPrincipal, perm);

            } else if (principalType.equals(principalToMatchTo.getClass().getCanonicalName())) {
                PermissionService.giveSpPrincipalPermission(mySpPrincipal, perm);
            }
        }
    }
}

From source file:com.ecyrd.jspwiki.auth.SecurityVerifier.java

/**
 * Verifies that a particular Principal possesses a Permission, as defined
 * in the security policy file.//from   w  w  w.j a  v  a 2  s.  c o  m
 * @param principal the principal
 * @param permission the permission
 * @return the result, based on consultation with the active Java security
 *         policy
 */
protected final boolean verifyStaticPermission(Principal principal, final Permission permission) {
    Subject subject = new Subject();
    subject.getPrincipals().add(principal);
    boolean allowedByGlobalPolicy = ((Boolean) Subject.doAsPrivileged(subject, new PrivilegedAction<Object>() {
        public Object run() {
            try {
                AccessController.checkPermission(permission);
                return Boolean.TRUE;
            } catch (AccessControlException e) {
                return Boolean.FALSE;
            }
        }
    }, null)).booleanValue();

    if (allowedByGlobalPolicy) {
        return true;
    }

    // Check local policy
    Principal[] principals = new Principal[] { principal };
    return m_engine.getAuthorizationManager().allowedByLocalPolicy(principals, permission);
}

From source file:org.atricore.idbus.kernel.main.authn.AuthenticatorImpl.java

/**
 * Validates user identity.  Populates the Subject with Principal and Credential information.
 *
 * @param credentials the credentials to be checked
 * @param schemeName  the authentication scheme to be used to check the supplied credentials.
 *//*from   w ww.  j  a v  a 2s  .com*/
public Subject check(Credential[] credentials, String schemeName) throws SSOAuthenticationException {

    // Initialize the AuthenticationScheme
    Subject s = new Subject();

    List<AuthenticationScheme> schemes = getSchemes(schemeName);
    Set<SSOPolicyEnforcementStatement> ssoPolicies = new HashSet<SSOPolicyEnforcementStatement>();
    String lastPrincipal = null;

    for (AuthenticationScheme scheme : schemes) {

        if (logger.isTraceEnabled())
            logger.trace("Authenticating with " + scheme);

        scheme.initialize(credentials, s);

        if (scheme.authenticate()) {
            // If authentication succeeds, return the subject.
            scheme.confirm();
            _authCount++;

            // Add all SSO Policies to authenticated Subject
            s.getPrincipals().addAll(scheme.getSSOPolicies());
            return s;
        }

        scheme.cancel();
        if (scheme.getSSOPolicies() != null) {
            ssoPolicies.addAll(scheme.getSSOPolicies());
        }
        if (scheme.getPrincipal() != null)
            lastPrincipal = scheme.getPrincipal().getName();

    }
    // Send SSO Policies with Authn error
    _authFailures++;
    throw new AuthenticationFailureException(lastPrincipal, lastPrincipal, ssoPolicies);

}

From source file:org.opengroupware.logic.auth.OGoLoginTokenManager.java

/**
 * Creates a new token for the given subject / environment.
 * /*from  w  ww.  j a va 2  s .c  o  m*/
 * @param _subject - the JAAS subject which contains the principals
 * @param _env     - an optional environment
 * @return the token String as inserted in the database
 */
public String createToken(Subject _subject, Object _env) {
    // TBD: createToken must take a *Subject* (or LoginContext), and not do the
    //      auth
    if (_subject == null)
        return null;

    String envext = _env != null ? NSPropertyListSerialization.stringFromPropertyList(_env) : null;

    Date now = new Date();
    Number uid = null;

    /* generate token */

    StringBuilder msg = new StringBuilder(1024);
    for (Principal p : _subject.getPrincipals()) {
        msg.append(p.getName());
        if (p instanceof IOGoPrincipal) {
            // TBD: check DB identifier
            Number pid = ((IOGoPrincipal) p).id();
            msg.append(pid);
            if (p instanceof OGoAccountPrincipal) {
                if (uid == null)
                    uid = pid;
                else if (!uid.equals(pid))
                    log.error("multiple account principals!");
            }
        }
    }
    if (uid == null) {
        log.error("did not find a primary principal in subject!");
        return null;
    }
    msg.append(now.getTime());
    if (envext != null)
        msg.append(envext);

    String token = UString.md5HashForString(msg.toString());
    msg = null;

    /* insert token into database */

    Map<String, Object> record = new HashMap<String, Object>(16);
    record.put("token", token);
    record.put("account_id", uid);
    record.put("creation_date", now);
    record.put("touch_date", now);
    if (envext != null)
        record.put("environment", envext);

    if (!this.db.adaptor().insertRow("login_token", record)) {
        log.error("could not insert login token into database: " + _subject);
        return null;
    }

    /* token is inserted, we are done */

    return token;
}

From source file:org.forgerock.openam.jaspi.modules.session.LocalSSOTokenSessionModule.java

/**
 * Validates the request by attempting to retrieve the SSOToken ID from the cookies on the request.
 * If the SSOToken ID cookie is not present then the method returns AuthStatus.SEND_FAILURE, otherwise if it is
 * present it is then used to retrieve the actual SSOToken from the SSOTokenManager, if valid then
 * AuthStatus.SUCCESS will be returned, otherwise AuthStatus.SEND_FAILURE will be returned.
 *
 * @param request The HttpServletRequest.
 * @param messageInfo A contextual object that encapsulates the client request and server response objects, and
 *                    that may be used to save state across a sequence of calls made to the methods of this
 *                    interface for the purpose of completing a secure message exchange.
 * @param clientSubject A Subject that represents the source of the service request. It is used by the method
 *                      implementation to store Principals and credentials validated in the request.
 * @return AuthStatus.SUCCESS if the SSOToken ID is valid, otherwise AuthStatus.SEND_FAILURE.
 * @throws AuthException If there is a problem validating the request.
 *///from w  ww . j  av a  2  s  .  c o m
private AuthStatus validate(HttpServletRequest request, MessageInfo messageInfo, Subject clientSubject)
        throws AuthException {

    String tokenId = getRequestUtils().getTokenId(request);
    if (StringUtils.isEmpty(tokenId)) {
        tokenId = request.getHeader(getCookieHeaderName());
    }
    if (!StringUtils.isEmpty(tokenId)) {
        SSOToken ssoToken = getFactory().getTokenFromId(tokenId);

        if (ssoToken != null) {

            int authLevel;
            try {
                authLevel = ssoToken.getAuthLevel();
                String name = ssoToken.getPrincipal().getName();
                handler.handle(new Callback[] { new CallerPrincipalCallback(clientSubject, name) });

                clientSubject.getPrincipals().add(ssoToken.getPrincipal());
            } catch (SSOException e) {
                throw new AuthException(e.getMessage());
            } catch (UnsupportedCallbackException e) {
                throw new AuthException(e.getMessage());
            } catch (IOException e) {
                throw new AuthException(e.getMessage());
            }

            Map<String, Object> context = (Map<String, Object>) messageInfo.getMap()
                    .get("org.forgerock.authentication.context");
            context.put("authLevel", authLevel);
            context.put("tokenId", ssoToken.getTokenID().toString());
            //TODO add more properties to context map

            return AuthStatus.SUCCESS;
        }
    }
    return AuthStatus.SEND_FAILURE;
}

From source file:org.betaconceptframework.astroboa.engine.jcr.dao.RepositoryDao.java

private void initializeIdentityStoreForRepository(CmsRepository cmsRepository) {

    if (StringUtils.isBlank(cmsRepository.getExternalIdentityStoreJNDIName())) {
        String identityStoreRepositoryId = cmsRepository.getIdentityStoreRepositoryId();

        if (StringUtils.isBlank(identityStoreRepositoryId)) {
            throw new CmsException(
                    "No external IdentityStore JNDI has been provided nor an identity store repository id for repository "
                            + cmsRepository.getId());
        }//from  www .  j  a va 2s  . co  m

        if (!repositoryInfos.containsKey(identityStoreRepositoryId)) {
            throw new CmsException("Found no repository with id " + identityStoreRepositoryId
                    + ".Cannot initialize identity store for repository " + cmsRepository.getId());
        }

        CmsRepository cmsRepositoryIdentityStore = repositoryInfos.get(identityStoreRepositoryId);
        Subject subject = new Subject();
        subject.getPrincipals().add(new IdentityPrincipal(IdentityPrincipal.SYSTEM));

        Group rolesPrincipal = new CmsGroup(AstroboaPrincipalName.Roles.toString());

        for (CmsRole cmsRole : CmsRole.values()) {
            rolesPrincipal.addMember(new CmsPrincipal(CmsRoleAffiliationFactory.INSTANCE
                    .getCmsRoleAffiliationForRepository(cmsRole, identityStoreRepositoryId)));
        }

        subject.getPrincipals().add(rolesPrincipal);

        SecurityContext securityContext = new SecurityContext(identityStoreRepositoryId, subject, 30, null);

        RepositoryContext repositoryContext = new RepositoryContext(cmsRepositoryIdentityStore,
                securityContext);
        AstroboaClientContextHolder
                .registerClientContext(new AstroboaClientContext(repositoryContext, lazyLoader), true);
        cmsRepositoryInitializationManager.initializeIdentityStore(cmsRepository.getId(),
                cmsRepositoryIdentityStore);
        AstroboaClientContextHolder.clearContext();
    }
}

From source file:org.forgerock.openidm.jaspi.modules.IDMJaspiModuleWrapper.java

/**
 * Provides IDM specific authentication process handling, by setting whether to log the client's IP address,
 * and then calls the underlying auth module's validateRequest method. If the auth module returns
 * SUCCESS, based on the authentication configuration will perform role calculation and, if present, will run the
 * augment security context script.//from www  .j a v  a 2 s  .co  m
 *
 * @param messageInfo {@inheritDoc}
 * @param clientSubject {@inheritDoc}
 * @param serviceSubject {@inheritDoc}
 * @return {@inheritDoc}
 * @throws AuthException {@inheritDoc}
 */
@SuppressWarnings("unchecked")
@Override
public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject)
        throws AuthException {

    // Add this properties so the AuditLogger knows whether to log the client IP in the header.
    setClientIPAddress(messageInfo);

    final AuthStatus authStatus = authModule.validateRequest(messageInfo, clientSubject, serviceSubject);

    if (!AuthStatus.SUCCESS.equals(authStatus)) {
        return authStatus;
    }

    String principalName = null;
    for (Principal principal : clientSubject.getPrincipals()) {
        if (principal.getName() != null) {
            principalName = principal.getName();
            break;
        }
    }

    if (principalName == null) {
        // As per Jaspi spec, the module developer MUST ensure that the client
        // subject's principal is set when the module returns SUCCESS.
        throw new JaspiAuthException(
                "Underlying Server Auth Module has not set the client subject's principal!");
    }

    // user is authenticated; populate security context

    try {
        final Resource resource = getAuthenticatedResource(principalName, messageInfo);

        final SecurityContextMapper securityContextMapper = SecurityContextMapper.fromMessageInfo(messageInfo)
                .setAuthenticationId(principalName);

        // Calculate (and set) roles if not already set
        if (securityContextMapper.getRoles() == null || securityContextMapper.getRoles().isEmpty()) {
            roleCalculator.calculateRoles(principalName, securityContextMapper, resource);
        }

        // set "resource" (component) if not already set
        if (securityContextMapper.getResource() == null) {
            securityContextMapper.setResource(queryOnResource);
        }

        // set "user id" (authorization.id) if not already set
        if (securityContextMapper.getUserId() == null) {
            if (resource != null) {
                // assign authorization id from resource if present
                securityContextMapper.setUserId(resource.getId() != null ? resource.getId()
                        : resource.getContent().get(FIELD_CONTENT_ID).asString());
            } else {
                // set to principal otherwise
                securityContextMapper.setUserId(principalName);
            }
        }

        // run the augmentation script, if configured (will no-op if none specified)
        augmentationScriptExecutor.executeAugmentationScript(augmentScript, properties, securityContextMapper);

    } catch (ResourceException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Failed role calculation for {} on {}.", principalName, queryOnResource, e);
        }
        if (e.isServerError()) { // HTTP server-side error; AuthException sadly does not accept cause
            throw new JaspiAuthException("Failed pass-through authentication of " + principalName + " on "
                    + queryOnResource + ":" + e.getMessage(), e);
        }
        // role calculation failed
        return AuthStatus.SEND_FAILURE;
    }

    return authStatus;
}

From source file:org.betaconceptframework.astroboa.engine.jcr.dao.RepositoryDao.java

/**   
 *   Subject authorization at this level is restricted only to authorize user
 *   whether she can or cannot login to the specified repository.
 *   Our default policy is a PERMIT REPOSITORY policy, meaning that an authenticated user
 *   has access to REPOSITORY available repositoryInfos defined within a Astroboa Server.
 *
 *   In cases where an authenticated user has access to a subset of available repositoryInfos
 *   then a {@link Group} named after "AuthorizedRepositories" must exist 
 *  among {@link Subject} principals. //from  w w w. ja v  a 2s.co  m
 *  
 *  If so, only and only if the specified repository exists inside this list,
 *  the user will be authorized to use Astroboa services for that repository.
 */
private void authorizeSubject(Subject subject, String repositoryId) {

    if (subject == null) {
        throw new CmsException("No subject provided ");
    }

    //In case authenticated
    Set<Principal> principals = subject.getPrincipals();

    if (CollectionUtils.isNotEmpty(principals)) {

        for (Principal principal : principals) {

            if (principal instanceof Group
                    && AstroboaPrincipalName.AuthorizedRepositories.toString().equals(principal.getName())) {

                //Found authorized repositoryInfos
                boolean userIsAuthorizedToAccessRepository = false;

                for (Enumeration<? extends Principal> authorizedRepositories = ((Group) principal)
                        .members(); authorizedRepositories.hasMoreElements();) {
                    Principal authorizedRepository = authorizedRepositories.nextElement();

                    if (StringUtils.equals(authorizedRepository.getName(), repositoryId)) {
                        userIsAuthorizedToAccessRepository = true;
                        break;
                    }
                }

                if (!userIsAuthorizedToAccessRepository) {
                    throw new CmsUnauthorizedRepositoryUseException(repositoryId);
                }
            }
        }
    }

}