org.jasig.cas.authentication.principal.Principal Java Examples

The following examples show how to use org.jasig.cas.authentication.principal.Principal. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PolicyBasedAuthenticationManager.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
protected Principal resolvePrincipal(
        final String handlerName, final PrincipalResolver resolver, final Credential credential) {
    if (resolver.supports(credential)) {
        logger.info("{} resolved from {}", resolver, credential);
        try {
            final Principal p = resolver.resolve(credential);
            logger.debug("{} resolved {} from {}", resolver, p, credential);
            logger.info("{} resolved {} from {}", resolver, p, credential);
            return p;
        } catch (final Exception e) {
            logger.error("{} failed to resolve principal from {}", resolver, credential, e);
        }
    } else {
        logger.warn(
                "{} is configured to use {} but it does not support {}, which suggests a configuration problem.",
                handlerName,
                resolver,
                credential);
        logger.info(
                "{} is configured to use {} but it does not support {}, which suggests a configuration problem.",
                handlerName,
                resolver,
                credential);
    }
    return null;
}
 
Example #2
Source File: DefaultHandlerResult.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Instantiates a new handler result.
 *
 * @param source the source
 * @param metaData the meta data
 * @param p the p
 * @param warnings the warnings
 */
public DefaultHandlerResult(
        final AuthenticationHandler source,
        final CredentialMetaData metaData,
        final Principal p,
        final List<MessageDescriptor> warnings) {
    Assert.notNull(source, "Source cannot be null.");
    Assert.notNull(metaData, "Credential metadata cannot be null.");
    this.handlerName = source.getName();
    if (!StringUtils.hasText(this.handlerName)) {
        this.handlerName = source.getClass().getSimpleName();
    }
    this.credentialMetaData = metaData;
    this.principal = p;
    this.warnings = warnings;
}
 
Example #3
Source File: OpenIdCredentialsAuthenticationHandler.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Override
public HandlerResult authenticate(final Credential credential) throws GeneralSecurityException {
    final OpenIdCredential c = (OpenIdCredential) credential;

    final TicketGrantingTicket t = this.ticketRegistry.getTicket(c.getTicketGrantingTicketId(),
                    TicketGrantingTicket.class);

    if (t == null || t.isExpired()) {
        throw new FailedLoginException("TGT is null or expired.");
    }
    final Principal principal = t.getAuthentication().getPrincipal();
    if (!principal.getId().equals(c.getUsername())) {
        throw new FailedLoginException("Principal ID mismatch");
    }
    return new HandlerResult(this, new BasicCredentialMetaData(c), principal);
}
 
Example #4
Source File: MultiFactorCredentialsTests.java    From cas-mfa with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultifactorAddMatchingCredentials() {
    final Principal firstPrincipal =  new DefaultPrincipalFactory().createPrincipal("casuser");

    final Authentication firstAuthentication = mock(Authentication.class);
    when(firstAuthentication.getPrincipal()).thenReturn(firstPrincipal);

    final Principal secondPrincipal =  new DefaultPrincipalFactory().createPrincipal("casuser");

    final Authentication secondAuthentication = mock(Authentication.class);
    when(secondAuthentication.getPrincipal()).thenReturn(secondPrincipal);

    final MultiFactorCredentials c = new MultiFactorCredentials();
    c.addAuthenticationToChain(firstAuthentication);
    c.addAuthenticationToChain(secondAuthentication);
    assertEquals(2, c.countChainedAuthentications());
}
 
Example #5
Source File: PrincipalAttributeRegisteredServiceUsernameProvider.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Override
public String resolveUsername(final Principal principal, final Service service) {
    String principalId = principal.getId();
    
    if (principal.getAttributes().containsKey(this.usernameAttribute)) {
        principalId = principal.getAttributes().get(this.usernameAttribute).toString();
    } else {
        logger.warn("Principal [{}] did not have attribute [{}] among attributes [{}] so CAS cannot "
                + "provide the user attribute the service expects. "
                + "CAS will instead return the default principal id [{}]",
                principalId,
                this.usernameAttribute,
                principal.getAttributes(),
                principalId);
    }
    
    logger.debug("Principal id to return is [{}]. The default principal id is [{}].",
            principalId, principal.getId());
    return principalId;
}
 
Example #6
Source File: ImmutableAuthentication.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Creates a new instance with the given data.
 *
 * @param date Non-null authentication date.
 * @param credentials Non-null list of credential metadata containing at least one entry.
 * @param principal Non-null authenticated principal.
 * @param attributes Nullable map of authentication metadata.
 * @param successes Non-null map of authentication successes containing at least one entry.
 * @param failures Nullable map of authentication failures.
 */
public ImmutableAuthentication(
        final DateTime date,
        final List<CredentialMetaData> credentials,
        final Principal principal,
        final Map<String, Object> attributes,
        final Map<String, HandlerResult> successes,
        final Map<String, Class<? extends Exception>> failures) {

    Assert.notNull(date, "Date cannot be null");
    Assert.notNull(credentials, "Credential cannot be null");
    Assert.notNull(principal, "Principal cannot be null");
    Assert.notNull(successes, "Successes cannot be null");
    Assert.notEmpty(credentials, "Credential cannot be empty");
    Assert.notEmpty(successes, "Successes cannot be empty");

    this.authenticationDate = date.toDate().getTime();
    this.credentials = credentials;
    this.principal = principal;
    this.attributes = attributes.isEmpty() ? null : attributes;
    this.successes = successes;
    this.failures = failures.isEmpty() ? null : failures;
}
 
Example #7
Source File: PolicyBasedAuthenticationManagerTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Creates a new named mock authentication handler that either successfully validates all credentials or fails to
 * validate all credentials.
 *
 * @param name Authentication handler name.
 * @param success True to authenticate all credentials, false to fail all credentials.
 *
 * @return New mock authentication handler instance.
 *
 * @throws Exception On errors.
 */
private static AuthenticationHandler newMockHandler(final String name, final boolean success) throws Exception {
    final AuthenticationHandler mock = mock(AuthenticationHandler.class);
    when(mock.getName()).thenReturn(name);
    when(mock.supports(any(Credential.class))).thenReturn(true);
    if (success) {
        final Principal p = new DefaultPrincipalFactory().createPrincipal("nobody");

        final HandlerResult result = new DefaultHandlerResult(
                mock,
                mock(CredentialMetaData.class),
                p);
        when(mock.authenticate(any(Credential.class))).thenReturn(result);
    } else {
        when(mock.authenticate(any(Credential.class))).thenThrow(new FailedLoginException());
    }
    return mock;
}
 
Example #8
Source File: OpenIdCredentialsAuthenticationHandler.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Override
public HandlerResult authenticate(final Credential credential) throws GeneralSecurityException {
    final OpenIdCredential c = (OpenIdCredential) credential;

    final TicketGrantingTicket t = this.ticketRegistry.getTicket(c.getTicketGrantingTicketId(),
                    TicketGrantingTicket.class);

    if (t == null || t.isExpired()) {
        throw new FailedLoginException("TGT is null or expired.");
    }
    final Principal principal = t.getAuthentication().getPrincipal();
    if (!principal.getId().equals(c.getUsername())) {
        throw new FailedLoginException("Principal ID mismatch");
    }
    return new DefaultHandlerResult(this, new BasicCredentialMetaData(c), principal);
}
 
Example #9
Source File: AbstractRegisteredServiceTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifyServiceAttributeFilterAllAttributes() {
    prepareService();
    this.r.setAttributeReleasePolicy(new ReturnAllAttributeReleasePolicy());
    final Principal p = mock(Principal.class);
    
    final Map<String, Object> map = new HashMap<>();
    map.put("attr1", "value1");
    map.put("attr2", "value2");
    map.put("attr3", Arrays.asList("v3", "v4"));
    
    when(p.getAttributes()).thenReturn(map);
    when(p.getId()).thenReturn("principalId");
    
    final Map<String, Object> attr = this.r.getAttributeReleasePolicy().getAttributes(p);
    assertEquals(attr.size(), map.size());
}
 
Example #10
Source File: AttributeReleasePolicyTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifyServiceAttributeFilterAllowedAttributes() {
    final ReturnAllowedAttributeReleasePolicy policy = new ReturnAllowedAttributeReleasePolicy();
    policy.setAllowedAttributes(Arrays.asList("attr1", "attr3"));
    final Principal p = mock(Principal.class);
    
    final Map<String, Object> map = new HashMap<>();
    map.put("attr1", "value1");
    map.put("attr2", "value2");
    map.put("attr3", Arrays.asList("v3", "v4"));
    
    when(p.getAttributes()).thenReturn(map);
    when(p.getId()).thenReturn("principalId");
    
    final Map<String, Object> attr = policy.getAttributes(p);
    assertEquals(attr.size(), 2);
    assertTrue(attr.containsKey("attr1"));
    assertTrue(attr.containsKey("attr3"));
    
    final byte[] data = SerializationUtils.serialize(policy);
    final ReturnAllowedAttributeReleasePolicy p2 = SerializationUtils.deserialize(data);
    assertNotNull(p2);
    assertEquals(p2.getAllowedAttributes(), policy.getAllowedAttributes());
}
 
Example #11
Source File: PrincipalAttributeRegisteredServiceUsernameProviderTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifyUsernameByPrincipalAttribute() {
    final PrincipalAttributeRegisteredServiceUsernameProvider provider =
            new PrincipalAttributeRegisteredServiceUsernameProvider("cn");
    
    final Map<String, Object> attrs = new HashMap<>();
    attrs.put("userid", "u1");
    attrs.put("cn", "TheName");
    
    final Principal p = mock(Principal.class);
    when(p.getId()).thenReturn("person");
    when(p.getAttributes()).thenReturn(attrs);
    
    final String id = provider.resolveUsername(p, TestUtils.getService());
    assertEquals(id, "TheName");
    
}
 
Example #12
Source File: ImmutableAuthentication.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new instance with the given data.
 *
 * @param date Non-null authentication date.
 * @param credentials Non-null list of credential metadata containing at least one entry.
 * @param principal Non-null authenticated principal.
 * @param attributes Nullable map of authentication metadata.
 * @param successes Non-null map of authentication successes containing at least one entry.
 * @param failures Nullable map of authentication failures.
 */
public ImmutableAuthentication(
        final Date date,
        final List<CredentialMetaData> credentials,
        final Principal principal,
        final Map<String, Object> attributes,
        final Map<String, HandlerResult> successes,
        final Map<String, Class<? extends Exception>> failures) {

    Assert.notNull(date, "Date cannot be null");
    Assert.notNull(credentials, "Credential cannot be null");
    Assert.notNull(principal, "Principal cannot be null");
    Assert.notNull(successes, "Successes cannot be null");
    Assert.notEmpty(credentials, "Credential cannot be empty");
    Assert.notEmpty(successes, "Successes cannot be empty");

    this.authenticatedDate = date.getTime();
    this.credentials = credentials;
    this.principal = principal;
    this.attributes = attributes.isEmpty() ? null : attributes;
    this.successes = successes;
    this.failures = failures.isEmpty() ? null : failures;
}
 
Example #13
Source File: SamlAuthenticationMetaDataPopulatorTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
private static AuthenticationBuilder newAuthenticationBuilder(final Principal principal) {
    final CredentialMetaData meta = new BasicCredentialMetaData(new UsernamePasswordCredential());
    final AuthenticationHandler handler = new SimpleTestUsernamePasswordAuthenticationHandler();
    return new DefaultAuthenticationBuilder(principal)
            .addCredential(meta)
            .addSuccess("test", new DefaultHandlerResult(handler, meta));
}
 
Example #14
Source File: LdapAuthenticationHandler.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a CAS principal with attributes if the LDAP entry contains principal attributes.
 *
 * @param username Username that was successfully authenticated which is used for principal ID when
 *                 {@link #setPrincipalIdAttribute(String)} is not specified.
 * @param ldapEntry LDAP entry that may contain principal attributes.
 *
 * @return Principal if the LDAP entry contains at least a principal ID attribute value, null otherwise.
 *
 * @throws LoginException On security policy errors related to principal creation.
 */
protected Principal createPrincipal(final String username, final LdapEntry ldapEntry) throws LoginException {
    final String id;
    if (this.principalIdAttribute != null) {
        final LdapAttribute principalAttr = ldapEntry.getAttribute(this.principalIdAttribute);
        if (principalAttr == null || principalAttr.size() == 0) {
            throw new LoginException(this.principalIdAttribute + " attribute not found for " + username);
        }
        if (principalAttr.size() > 1) {
            if (this.allowMultiplePrincipalAttributeValues) {
                logger.warn(
                        "Found multiple values for principal ID attribute: {}. Using first value={}.",
                        principalAttr,
                        principalAttr.getStringValue());
            } else {
                throw new LoginException("Multiple principal values not allowed: " + principalAttr);
            }
        }
        id = principalAttr.getStringValue();
    } else {
        id = username;
    }
    final Map<String, Object> attributeMap = new LinkedHashMap<String, Object>(this.principalAttributeMap.size());
    for (String ldapAttrName : this.principalAttributeMap.keySet()) {
        final LdapAttribute attr = ldapEntry.getAttribute(ldapAttrName);
        if (attr != null) {
            logger.debug("Found principal attribute: {}", attr);
            final String principalAttrName = this.principalAttributeMap.get(ldapAttrName);
            if (attr.size() > 1) {
                attributeMap.put(principalAttrName, attr.getStringValues());
            } else {
                attributeMap.put(principalAttrName, attr.getStringValue());
            }
        }
    }
    return new SimplePrincipal(id, attributeMap);
}
 
Example #15
Source File: MultifactorLoginViewPrincipalAttributeGreeter.java    From cas-mfa with Apache License 2.0 5 votes vote down vote up
@Override
public String getPersonToGreet(final Principal p, final MessageContext messageContext) {

    String personId = p.getId();
    final Object attrValue = p.getAttributes().get(this.greetingAttributeName);

    if (attrValue == null) {
        LOGGER.warn("No attribute value could be found for [{}]", this.greetingAttributeName);
        return p.getId();
    }

    String greetingPersonId = attrValue.toString();
    if (attrValue instanceof Collection) {
        final Collection col =((Collection) attrValue);
        if (!col.isEmpty()) {
            greetingPersonId = col.iterator().next().toString();
            LOGGER.warn("Found multiple attribute values [{}] for [{}] to greet. Picked [{}]",
                    attrValue, this.greetingAttributeName,
                    greetingPersonId);
        }
    }

    if (!StringUtils.isBlank(greetingPersonId)) {
        personId = greetingPersonId;
    }

    final MessageResolver resolver = new MessageBuilder().source(CODE).info().code(CODE).arg(personId).build();
    messageContext.addMessage(resolver);

    final Message[] messages = messageContext.getMessagesBySource(CODE);
    if (messages == null || messages.length == 0) {
        LOGGER.warn("The greeting message for principal [{}] could not be resolved by the "
                + "code [{}] in any of the configured message resource bundles. Falling back to principal id [{}]",
                p, CODE, p.getId());
        return p.getId();
    }
    return messages[0].getText();
}
 
Example #16
Source File: OauthPersonDirectoryPrincipalResolver.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Override
public Principal resolve(Credential credential) {
    logger.debug("Attempting to resolve a principal...");

    if (credential instanceof ClientCredential){
        // do nothing
    } else {
        throw new RuntimeException("用户数据转换异常!");
    }

    ClientCredential oauthCredential = (ClientCredential) credential;
    UserProfile userProfile = oauthCredential.getUserProfile();
    logger.info("userProfile = {}", userProfile);


    //String principalId = oauthCredential.getUserProfile().getId();
    String principalId = oauthCredential.getId();
    if (principalId == null) {
        logger.debug("Got null for extracted principal ID; returning null.");
        return null;
    }

    logger.debug("Creating SimplePrincipal for [{}]", principalId);
    //UserProfile userProfile = oauthCredential.getUserProfile();
    final Map<String, Object> attributes = userProfile.getAttributes();

    if (attributes == null & !this.returnNullIfNoAttributes) {
        return new SimplePrincipal(principalId);
    }

    if (attributes == null) {
        return null;
    }

    return new SimplePrincipal(principalId, attributes);
}
 
Example #17
Source File: SpnegoCredentialsTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
public void testToStringWithPrincipal() {
    final SpnegoCredential credentials = new SpnegoCredential(new byte[] {});
    final Principal principal = new SimplePrincipal("test");
    credentials.setPrincipal(principal);
    assertEquals("test", credentials.toString());
}
 
Example #18
Source File: DefaultCompositeAuthenticationTests.java    From cas-mfa with Apache License 2.0 5 votes vote down vote up
public DefaultCompositeAuthenticationTests() {

        final Map map = mock(Map.class);
        final Principal p = mock(Principal.class);
        when(p.getId()).thenReturn("casuser");
        when(p.getAttributes()).thenReturn(map);

        final Map authnAttrs = mock(Map.class);
        this.authentication = new DefaultCompositeAuthentication(p, authnAttrs, new ArrayList(), new HashMap(), new HashMap());
    }
 
Example #19
Source File: ClientAuthenticationHandlerTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyOk() throws GeneralSecurityException, PreventedException {
    final FacebookProfile facebookProfile = new FacebookProfile();
    facebookProfile.setId(ID);
    this.fbClient.setFacebookProfile(facebookProfile);
    final HandlerResult result = this.handler.authenticate(this.clientCredential);
    final Principal principal = result.getPrincipal();
    assertEquals(FacebookProfile.class.getSimpleName() + "#" + ID, principal.getId());
}
 
Example #20
Source File: JpaTicketRegistryTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
static TicketGrantingTicket newTGT() {
    final Principal principal = new SimplePrincipal(
            "bob", Collections.singletonMap("displayName", (Object) "Bob"));
    return new TicketGrantingTicketImpl(
            ID_GENERATOR.getNewTicketId("TGT"),
            TestUtils.getAuthentication(principal),
            EXP_POLICY_TGT);
}
 
Example #21
Source File: PolicyBasedAuthenticationManager.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
@Audit(
    action="AUTHENTICATION",
    actionResolverName="AUTHENTICATION_RESOLVER",
    resourceResolverName="AUTHENTICATION_RESOURCE_RESOLVER")
@Profiled(tag = "AUTHENTICATE", logFailuresSeparately = false)
public final Authentication authenticate(final Credential... credentials) throws AuthenticationException {

    final AuthenticationBuilder builder = authenticateInternal(credentials);
    final Authentication authentication = builder.build();
    final Principal principal = authentication.getPrincipal();
    if (principal  instanceof NullPrincipal) {
        throw new UnresolvedPrincipalException(authentication);
    }

    for (final HandlerResult result : authentication.getSuccesses().values()) {
        builder.addAttribute(AUTHENTICATION_METHOD_ATTRIBUTE, result.getHandlerName());
    }

    logger.info("Authenticated {} with credentials {}.", principal, Arrays.asList(credentials));
    logger.debug("Attribute map for {}: {}", principal.getId(), principal.getAttributes());

    for (final AuthenticationMetaDataPopulator populator : this.authenticationMetaDataPopulators) {
        for (final Credential credential : credentials) {
            populator.populateAttributes(builder, credential);
        }
    }

    return builder.build();
}
 
Example #22
Source File: HandlerResult.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
public HandlerResult(
        final AuthenticationHandler source,
        final CredentialMetaData metaData,
        final Principal p,
        final List<Message> warnings) {
    Assert.notNull(source, "Source cannot be null.");
    Assert.notNull(metaData, "Credential metadata cannot be null.");
    this.handlerName = source.getName();
    if (!StringUtils.hasText(this.handlerName)) {
        this.handlerName = source.getClass().getSimpleName();
    }
    this.credentialMetaData = metaData;
    this.principal = p;
    this.warnings = warnings;
}
 
Example #23
Source File: MultifactorLoginViewPrincipalAttributeGreeterTests.java    From cas-mfa with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidPrincipalMultivaluedAttributeToGreet() {
    final Map map = new HashMap();
    map.put("firstName", Arrays.asList("cas", "sso"));
    map.put("lastName", "user");

    final Principal p = principalFactory.createPrincipal("userid", map);

    final MultifactorLoginViewPrincipalAttributeGreeter greeter = new MultifactorLoginViewPrincipalAttributeGreeter(
            "firstName");

    configureMessageContextForPrincipal("cas");
    final String value = greeter.getPersonToGreet(p, this.messageContext);
    assertTrue(value.contains("cas"));
}
 
Example #24
Source File: OAuth20ProfileControllerTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
public void testOK() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT
            + OAuthConstants.PROFILE_URL);
    mockRequest.setParameter(OAuthConstants.ACCESS_TOKEN, TGT_ID);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    final TicketRegistry ticketRegistry = mock(TicketRegistry.class);
    final TicketGrantingTicket ticketGrantingTicket = mock(TicketGrantingTicket.class);
    when(ticketGrantingTicket.isExpired()).thenReturn(false);
    when(ticketRegistry.getTicket(TGT_ID)).thenReturn(ticketGrantingTicket);
    final Authentication authentication = mock(Authentication.class);
    final Principal principal = mock(Principal.class);
    when(principal.getId()).thenReturn(ID);
    final Map<String, Object> map = new HashMap<String, Object>();
    map.put(NAME, VALUE);
    List<String> list = Arrays.asList(VALUE, VALUE);
    map.put(NAME2, list);
    when(principal.getAttributes()).thenReturn(map);
    when(authentication.getPrincipal()).thenReturn(principal);
    when(ticketGrantingTicket.getAuthentication()).thenReturn(authentication);
    oauth20WrapperController.setTicketRegistry(ticketRegistry);
    oauth20WrapperController.afterPropertiesSet();
    oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertEquals(200, mockResponse.getStatus());
    assertEquals(CONTENT_TYPE, mockResponse.getContentType());
    assertEquals("{\"id\":\"" + ID + "\",\"attributes\":[{\"" + NAME + "\":\"" + VALUE + "\"},{\"" + NAME2
            + "\":[\"" + VALUE + "\",\"" + VALUE + "\"]}]}", mockResponse.getContentAsString());
}
 
Example #25
Source File: LdapAuthenticationHandler.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Creates a CAS principal with attributes if the LDAP entry contains principal attributes.
 *
 * @param username Username that was successfully authenticated which is used for principal ID when
 *                 {@link #setPrincipalIdAttribute(String)} is not specified.
 * @param ldapEntry LDAP entry that may contain principal attributes.
 *
 * @return Principal if the LDAP entry contains at least a principal ID attribute value, null otherwise.
 *
 * @throws LoginException On security policy errors related to principal creation.
 */
protected Principal createPrincipal(final String username, final LdapEntry ldapEntry) throws LoginException {
    final String id;
    if (this.principalIdAttribute != null) {
        final LdapAttribute principalAttr = ldapEntry.getAttribute(this.principalIdAttribute);
        if (principalAttr == null || principalAttr.size() == 0) {
            throw new LoginException(this.principalIdAttribute + " attribute not found for " + username);
        }
        if (principalAttr.size() > 1) {
            if (this.allowMultiplePrincipalAttributeValues) {
                logger.warn(
                        "Found multiple values for principal ID attribute: {}. Using first value={}.",
                        principalAttr,
                        principalAttr.getStringValue());
            } else {
                throw new LoginException("Multiple principal values not allowed: " + principalAttr);
            }
        }
        id = principalAttr.getStringValue();
    } else {
        id = username;
    }
    final Map<String, Object> attributeMap = new LinkedHashMap<>(this.principalAttributeMap.size());
    for (final Map.Entry<String, String> ldapAttr : this.principalAttributeMap.entrySet()) {
        final LdapAttribute attr = ldapEntry.getAttribute(ldapAttr.getKey());
        if (attr != null) {
            logger.debug("Found principal attribute: {}", attr);
            final String principalAttrName = ldapAttr.getValue();
            if (attr.size() > 1) {
                attributeMap.put(principalAttrName, attr.getStringValues());
            } else {
                attributeMap.put(principalAttrName, attr.getStringValue());
            }
        }
    }
    return this.principalFactory.createPrincipal(id, attributeMap);
}
 
Example #26
Source File: TestUtils.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
public static Authentication getAuthentication(final Principal principal, final Map<String, Object> attributes) {
    final AuthenticationHandler handler = new SimpleTestUsernamePasswordAuthenticationHandler();
    final CredentialMetaData meta = new BasicCredentialMetaData(new UsernamePasswordCredential());
    return new DefaultAuthenticationBuilder(principal)
            .addCredential(meta)
            .addSuccess("testHandler", new DefaultHandlerResult(handler, meta))
            .setAttributes(attributes)
            .build();
}
 
Example #27
Source File: MultiFactorCredentials.java    From cas-mfa with Apache License 2.0 5 votes vote down vote up
/**
 * Enumerates the list of available principals in the authentication chain
 * and ensures that the newly given and provided principal is compliant
 * and equals the rest of the principals in the chain. The match
 * is explicitly controlled by {@link Principal#equals(Object)}
 * implementation.
 *
 * @param authentication the authentication object whose principal is compared against the chain
 * @return true if no mismatch is found; false otherwise.
 */
private boolean doesPrincipalMatchAuthenticationChain(final Authentication authentication) {
    for (final Authentication authn : this.chainedAuthentication) {
        final Principal currentPrincipal = authn.getPrincipal();
        final Principal newPrincipal = authentication.getPrincipal();

        if (!currentPrincipal.equals(newPrincipal)) {
            return false;
        }
    }
    return true;
}
 
Example #28
Source File: AttributeReleasePolicyTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyAttributeFilterMappedAttributes() {
    final ReturnMappedAttributeReleasePolicy policy = new ReturnMappedAttributeReleasePolicy();
    final Map<String, String> mappedAttr = new HashMap<>();
    mappedAttr.put("attr1", "newAttr1");
    
    policy.setAllowedAttributes(mappedAttr);
            
    final Principal p = mock(Principal.class);
    
    final Map<String, Object> map = new HashMap<>();
    map.put("attr1", "value1");
    map.put("attr2", "value2");
    map.put("attr3", Arrays.asList("v3", "v4"));
    
    when(p.getAttributes()).thenReturn(map);
    when(p.getId()).thenReturn("principalId");
    
    final Map<String, Object> attr = policy.getAttributes(p);
    assertEquals(attr.size(), 1);
    assertTrue(attr.containsKey("newAttr1"));
    
    final byte[] data = SerializationUtils.serialize(policy);
    final ReturnMappedAttributeReleasePolicy p2 = SerializationUtils.deserialize(data);
    assertNotNull(p2);
    assertEquals(p2.getAllowedAttributes(), policy.getAllowedAttributes());
}
 
Example #29
Source File: AnonymousRegisteredServiceUsernameAttributeProviderTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyPrincipalResolution() {
    final AnonymousRegisteredServiceUsernameAttributeProvider provider =
            new AnonymousRegisteredServiceUsernameAttributeProvider(
            new ShibbolethCompatiblePersistentIdGenerator("casrox"));
    
    final Service service = mock(Service.class);
    when(service.getId()).thenReturn("id");
    final Principal principal = new DefaultPrincipalFactory().createPrincipal("uid");
    final String id = provider.resolveUsername(principal, service);
    assertNotNull(id);
}
 
Example #30
Source File: DefaultRegisteredServiceUsernameProviderTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyRegServiceUsername() {
    final DefaultRegisteredServiceUsernameProvider provider = 
            new DefaultRegisteredServiceUsernameProvider();
    
    final Principal principal = mock(Principal.class);
    when(principal.getId()).thenReturn("id");
    final String id = provider.resolveUsername(principal, TestUtils.getService());
    assertEquals(id, principal.getId());
}