List of usage examples for javax.security.auth Subject getPrincipals
public <T extends Principal> Set<T> getPrincipals(Class<T> c)
From source file:com.ideabase.repository.test.api.UserServiceTest.java
/** * Ensure user service can authenticate user credentials. * Successful authentication ended with a {@code User} profile object. *//* w w w.j a v a2s . c om*/ public void testLogin() { final String userName = "veryrandom-user" + Math.random(); final String password = DigestUtils.shaHex("password is md5"); // create user final Integer userId = TestCaseRepositoryHelper.fixCreateUser(mUserService, userName, password); // authenticate user final UserCredential userCredential = new UserCredential(userName, password); // authenticate user. final Subject subject = mUserService.login(userCredential); // retrieve user principal. final RepositoryUserPrincipal principal = subject.getPrincipals(RepositoryUserPrincipal.class).iterator() .next(); // verify assertNotNull("Authentication failed.", subject); assertNotNull("Authenticated user principal is null.", principal); assertNotNull("Authenticated user id is not attached with principal.", principal.getId()); LOG.debug("Subject - " + subject); }
From source file:org.atricore.idbus.capabilities.sso.support.federation.EmailAccountLinkEmitter.java
public AccountLink emit(Subject subject) { // If subjectName ID is email formatted, use it Set<SubjectNameID> nameIds = subject.getPrincipals(SubjectNameID.class); if (nameIds != null) { if (logger.isDebugEnabled()) logger.debug("SubjectNameID Pricipals found: " + nameIds.size()); for (SubjectNameID nameId : nameIds) { if (nameId.getFormat() == null || nameId.getFormat().equals(NameIDFormat.EMAIL.getValue())) { String email = nameId.getName(); return new DynamicAccountLinkImpl(subject, email.substring(0, email.indexOf("@")), NameIDFormat.UNSPECIFIED.getValue()); }//www . j av a 2 s. c o m } } // Look for subject attributes that may be an email (TODO : make configurable) Set<SubjectAttribute> subjectAttrs = subject.getPrincipals(SubjectAttribute.class); if (logger.isDebugEnabled()) logger.debug("SubjectAttribute Pricipals found: " + subjectAttrs.size()); for (SubjectAttribute subjectAttribute : subjectAttrs) { if (logger.isDebugEnabled()) { logger.debug("Pricipal Name: " + subjectAttribute.getName()); logger.debug("Pricipal Format: " + subjectAttribute.getValue()); } // TODO : Make configurable rules to take email from attributes !!! if (subjectAttribute.getName().startsWith("/UserAttribute[@ldap:targetAttribute=\"mail\"]") || subjectAttribute.getName().equalsIgnoreCase("emailaddress") || subjectAttribute.getName().equalsIgnoreCase("email") || subjectAttribute.getName().equalsIgnoreCase("mail") || subjectAttribute.getName().equalsIgnoreCase("urn:org:atricore:idbus:user:property:email")) { // Need to map email to local user name! String email = subjectAttribute.getValue(); if (logger.isDebugEnabled()) logger.debug("Found email as attribute [" + email + "]"); if (stripEmailDomain) return new DynamicAccountLinkImpl(subject, email.substring(0, email.indexOf("@")), NameIDFormat.UNSPECIFIED.getValue()); else return new DynamicAccountLinkImpl(subject, email, NameIDFormat.EMAIL.getValue()); } } // Try directly with the Subject ID Set<SubjectNameID> ids = subject.getPrincipals(SubjectNameID.class); if (ids != null && ids.size() > 0) { SubjectNameID id = ids.iterator().next(); String email = id.getName(); if (logger.isDebugEnabled()) logger.debug("Found email as subject id [" + email + "]"); return new DynamicAccountLinkImpl(subject, email.substring(0, email.indexOf("@")), NameIDFormat.UNSPECIFIED.getValue()); } /* Set<SubjectAttribute> idpAttrs = subject.getPrincipals(SubjectAttribute.class); for (SubjectAttribute idpAttr : idpAttrs) { if (idpAttr.getName().equals( DCEPACAttributeDefinition.PRINCIPAL.getValue() )) { return new DynamicAccountLinkImpl(subject, idpAttr.getValue() ); } } */ logger.error("Cannot create account link for subject : " + subject); return null; }
From source file:org.jbpm.security.authentication.SubjectAuthenticationService.java
public String getActorId() { if (actorId == null) { Subject subject = Subject.getSubject(AccessController.getContext()); if (subject == null) { log.warn("no subject exists! cannot get actorId"); return null; }// www . jav a 2s . com Set principals = subject.getPrincipals(principalClass); if (principals != null && !principals.isEmpty()) { // always use the first one (so be patient what Principal classes are used) Principal principal = (Principal) principals.iterator().next(); actorId = principal.getName(); } } return actorId; }
From source file:org.sakaiproject.nakamura.lite.jackrabbit.SparseLoginModule.java
@Override protected boolean impersonate(Principal principal, Credentials credentials) throws RepositoryException, LoginException { if (credentials instanceof AdministrativeCredentials) { return true; }//from ww w. j a v a 2 s . c o m if (credentials instanceof AnonCredentials) { return false; } LoginModulePlugin[] modules = Activator.getLoginModules(); for (int i = 0; i < modules.length; i++) { if (modules[i].canHandle(credentials)) { int result = modules[i].impersonate(principal, credentials); if (result != LoginModulePlugin.IMPERSONATION_DEFAULT) { return result == LoginModulePlugin.IMPERSONATION_SUCCESS; } } } User user = authenticator.systemAuthenticate(principal.getName()); if (user != null) { Subject impersSubject = getImpersonatorSubject(credentials); if (!impersSubject.getPrincipals(AdminPrincipal.class).isEmpty() || !impersSubject.getPrincipals(SystemPrincipal.class).isEmpty()) { return true; } String impersonators = (String) user.getProperty(User.IMPERSONATORS_FIELD); if (impersonators != null) { Set<String> imp = new HashSet<String>(); Collections.addAll(imp, StringUtils.split(impersonators, ';')); for (Principal p : subject.getPrincipals()) { if (imp.contains(p.getName())) { return true; } } } throw new FailedLoginException("attempt by user " + principal.getName() + " with subjects " + impersSubject.getPrincipals() + " to impersonate " + credentials); } return false; }
From source file:info.magnolia.cms.security.MgnlUserManager.java
/** * Initialize new user using JAAS authenticated/authorized subject * @param subject//from ww w . jav a 2 s . co m * @throws UnsupportedOperationException */ public User getUser(Subject subject) throws UnsupportedOperationException { User user = null; // this could be the case if no one is logged in yet if (subject == null) { return new DummyUser(); } Set principalSet = subject.getPrincipals(Entity.class); Iterator entityIterator = principalSet.iterator(); Entity userDetails = (Entity) entityIterator.next(); String name = (String) userDetails.getProperty(Entity.NAME); try { Content node = getHierarchyManager().getContent(name); user = new MgnlUser(node); ((MgnlUser) user).setLastAccess(); } catch (PathNotFoundException e) { log.error("user not registered in magnolia itself [" + name + "]"); } catch (Exception e) { log.error("can't get jcr-node of current user", e); } if (user == null) { user = new DummyUser(); } return user; }
From source file:org.atricore.idbus.capabilities.sso.main.emitter.plans.actions.BuildAuthnAssertionStatementsAction.java
@Override protected void doExecute(IdentityArtifact in, IdentityArtifact out, ExecutionContext executionContext) { logger.debug("starting action"); AssertionType assertion = (AssertionType) out.getContent(); // Do we have a SSOUser ? SecurityTokenProcessingContext stsCtx = (SecurityTokenProcessingContext) executionContext .getContextInstance().getTransientVariable(WSTConstants.VAR_EMISSION_CTX); Subject s = (Subject) executionContext.getContextInstance().getVariable(WSTConstants.SUBJECT_PROP); Set<SSOUser> ssoUsers = s.getPrincipals(SSOUser.class); if (ssoUsers == null || ssoUsers.size() != 1) throw new RuntimeException("Subject must contain a SSOUser principal"); SSOUser ssoUser = ssoUsers.iterator().next(); AttributeType attrPrincipal = new AttributeType(); attrPrincipal.setName(DCEPACAttributeDefinition.PRINCIPAL.getValue()); attrPrincipal.setNameFormat(AttributeNameFormat.URI.getValue()); attrPrincipal.getAttributeValue().add(ssoUser.getName()); // This will add SSO User properties as attribute statements. List<AttributeType> attrProps = new ArrayList<AttributeType>(); if (ssoUser.getProperties() != null && ssoUser.getProperties().length > 0) { // TODO : We could group some properties as multi valued attributes like, privileges! for (SSONameValuePair property : ssoUser.getProperties()) { AttributeType attrProp = new AttributeType(); attrProp.setName(SAMLR2Constants.SSOUSER_PROPERTY_NS + ":" + property.getName()); attrProp.setNameFormat(AttributeNameFormat.URI.getValue()); attrProp.getAttributeValue().add(property.getValue()); attrProps.add(attrProp);// w w w.j av a2s .c om } } // Groups Set<SSORole> ssoRoles = s.getPrincipals(SSORole.class); // Additional tokens List<AttributeType> attrTokens = new ArrayList<AttributeType>(); for (SecurityToken otherToken : stsCtx.getEmittedTokens()) { if (otherToken.getSerializedContent() != null && otherToken.getNameIdentifier() != null) { // Token Value { // This should be properly encoded !! AttributeType attrToken = new AttributeType(); if (otherToken.getNameIdentifier() != null) { if (otherToken.getNameIdentifier().equals(WSTConstants.WST_OAUTH2_TOKEN_TYPE)) { attrToken.setFriendlyName("OAUTH2"); } else { attrToken.setFriendlyName(otherToken.getNameIdentifier()); } } // Token by name identifier attrToken.setName(otherToken.getNameIdentifier()); attrToken.setNameFormat(AttributeNameFormat.URI.getValue()); attrToken.getAttributeValue().add(otherToken.getSerializedContent()); attrTokens.add(attrToken); } // Token ID { AttributeType attrTokenById = new AttributeType(); if (otherToken.getNameIdentifier() != null) { if (otherToken.getNameIdentifier().equals(WSTConstants.WST_OAUTH2_TOKEN_TYPE)) { attrTokenById.setFriendlyName("OAUTH2_ID"); } else { attrTokenById.setFriendlyName(otherToken.getNameIdentifier() + "_ID"); } } // Token by name identifier attrTokenById.setName(otherToken.getNameIdentifier() + "_ID"); attrTokenById.setNameFormat(AttributeNameFormat.URI.getValue()); attrTokenById.getAttributeValue().add(otherToken.getId()); attrTokens.add(attrTokenById); } } else { logger.debug("Ignoring token " + otherToken.getNameIdentifier()); } } AttributeType attrRole = new AttributeType(); // TODO : Make SAML Attribute profile configurable attrRole.setName(DCEPACAttributeDefinition.GROUPS.getValue()); attrRole.setNameFormat(AttributeNameFormat.URI.getValue()); for (SSORole role : ssoRoles) attrRole.getAttributeValue().add(role.getName()); // SSO Enforced policies // TODO : Can we use SAML Authn context information ?! List<AttributeType> attrPolicies = new ArrayList<AttributeType>(); Set<SSOPolicyEnforcementStatement> ssoPolicyEnforcements = s .getPrincipals(SSOPolicyEnforcementStatement.class); for (SSOPolicyEnforcementStatement ssoPolicyEnforcement : ssoPolicyEnforcements) { AttributeType attrPolicy = new AttributeType(); attrPolicy.setFriendlyName(ssoPolicyEnforcement.getName()); attrPolicy.setName(ssoPolicyEnforcement.getNs() + ":" + ssoPolicyEnforcement.getName()); attrPolicy.setNameFormat(AttributeNameFormat.URI.getValue()); if (ssoPolicyEnforcement.getValues().size() > 0) { for (Object v : ssoPolicyEnforcement.getValues()) attrPolicy.getAttributeValue().add(v); } attrPolicies.add(attrPolicy); } // Create attribute statements AttributeStatementType attributeStatement = new AttributeStatementType(); attributeStatement.getAttributeOrEncryptedAttribute().add(attrRole); attributeStatement.getAttributeOrEncryptedAttribute().add(attrPrincipal); if (attrTokens.size() > 0) for (AttributeType attrToken : attrTokens) attributeStatement.getAttributeOrEncryptedAttribute().add(attrToken); if (attrProps.size() > 0) { for (AttributeType attrProp : attrProps) attributeStatement.getAttributeOrEncryptedAttribute().add(attrProp); } if (attrPolicies.size() > 0) for (AttributeType attrPolicy : attrPolicies) attributeStatement.getAttributeOrEncryptedAttribute().add(attrPolicy); // Assembly all assertion.getStatementOrAuthnStatementOrAuthzDecisionStatement().add(attributeStatement); logger.debug("ending action"); }
From source file:org.apache.jackrabbit.core.security.principal.DefaultPrincipalProvider.java
/** * @see PrincipalProvider#canReadPrincipal(javax.jcr.Session,java.security.Principal) *///from w w w. j a v a2s . com public boolean canReadPrincipal(Session session, Principal principal) { checkInitialized(); // check if the session can read the user/group associated with the // given principal if (session instanceof SessionImpl) { SessionImpl sImpl = (SessionImpl) session; Subject subject = sImpl.getSubject(); if (!subject.getPrincipals(SystemPrincipal.class).isEmpty() || !subject.getPrincipals(AdminPrincipal.class).isEmpty()) { return true; } try { UserManager umgr = sImpl.getUserManager(); return umgr.getAuthorizable(principal) != null; } catch (RepositoryException e) { log.error("Failed to determine accessibility of Principal {}", principal, e); } } return false; }
From source file:fi.okm.mpass.shibboleth.authn.impl.ValidateWilmaResponseTest.java
/** * Test with valid response.//from w w w . j a v a 2 s.co m * @throws Exception */ @Test protected void testSuccess() throws Exception { action.initialize(); prc.getSubcontext(AuthenticationContext.class, false).setAttemptedFlow(authenticationFlows.get(0)); final WilmaAuthenticationContext wilmaContext = prc.getSubcontext(AuthenticationContext.class, false) .getSubcontext(WilmaAuthenticationContext.class, true); wilmaContext.setNonce(nonce); final Event event = action.execute(src); Assert.assertNull(event); final Subject subject = prc.getSubcontext(AuthenticationContext.class, false).getAuthenticationResult() .getSubject(); Assert.assertNotNull(subject); Set<UsernamePrincipal> principals = subject.getPrincipals(UsernamePrincipal.class); Assert.assertEquals(principals.size(), 1); Assert.assertEquals(principals.iterator().next().getName(), userid); }
From source file:org.infoscoop.web.SessionManagerFilter.java
private boolean isChangeLoginUser(String uid, Subject loginUser) { Set principals = loginUser.getPrincipals(ISPrincipal.class); for (Iterator it = principals.iterator(); it.hasNext();) { ISPrincipal p = (ISPrincipal) it.next(); if (ISPrincipal.UID_PRINCIPAL.equals(p.getType())) { if (uid != null && !uid.equals(p.getName())) return true; }/* ww w .j ava2 s .com*/ } return false; }
From source file:org.infoscoop.web.SessionManagerFilter.java
private String getUserNameFromSubject(Subject loginUser) { Collection principals = loginUser.getPrincipals(ISPrincipal.class); for (Iterator it = principals.iterator(); it.hasNext();) { ISPrincipal p = (ISPrincipal) it.next(); if (ISPrincipal.UID_PRINCIPAL.equals(p.getType())) { ISPrincipal isp = (ISPrincipal) p; return isp.getDisplayName(); }//from ww w. j av a 2 s . co m } return null; }