@SuppressWarnings("unchecked") @Override protected UserDetails loadUserDetails(final Assertion assertion) { final List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (final String attribute : this.attributes) { final Object value = assertion.getPrincipal().getAttributes().get(attribute); if (value == null) { continue; } if (value instanceof List) { final List list = (List) value; for (final Object o : list) { grantedAuthorities.add(new SimpleGrantedAuthority( this.convertToUpperCase ? o.toString().toUpperCase() : o .toString())); } } else { grantedAuthorities.add(new SimpleGrantedAuthority( this.convertToUpperCase ? value.toString().toUpperCase() : value .toString())); } } return new User(assertion.getPrincipal().getName(), NON_EXISTENT_PASSWORD_VALUE, true, true, true, true, grantedAuthorities); }
@Test public void correctlyExtractsNamedAttributesFromAssertionAndConvertsThemToAuthorities() { GrantedAuthorityFromAssertionAttributesUserDetailsService uds = new GrantedAuthorityFromAssertionAttributesUserDetailsService( new String[] { "a", "b", "c", "d" }); uds.setConvertToUpperCase(false); Assertion assertion = mock(Assertion.class); AttributePrincipal principal = mock(AttributePrincipal.class); Map<String, Object> attributes = new HashMap<>(); attributes.put("a", Arrays.asList("role_a1", "role_a2")); attributes.put("b", "role_b"); attributes.put("c", "role_c"); attributes.put("d", null); attributes.put("someother", "unused"); when(assertion.getPrincipal()).thenReturn(principal); when(principal.getAttributes()).thenReturn(attributes); when(principal.getName()).thenReturn("somebody"); CasAssertionAuthenticationToken token = new CasAssertionAuthenticationToken( assertion, "ticket"); UserDetails user = uds.loadUserDetails(token); Set<String> roles = AuthorityUtils.authorityListToSet(user.getAuthorities()); assertThat(roles).containsExactlyInAnyOrder( "role_a1", "role_a2", "role_b", "role_c"); } }
Object credObj = principal.getAttributes().get("credential"); if (credObj != null) { String clearPass = decryptPassword(credObj.toString());
}); Map<String, Object> attributes = casPrincipal.getAttributes();
@Override public boolean isUserInRole(final String role, final Scope scope) { if (roleAttribute != null) { final Object value = principal.getAttributes().get(roleAttribute); if (value instanceof Collection) { return ((Collection) value).contains(role); } else if (value instanceof String) { return value.equals(role); } } return false; }
/** * Retrieves the attributes for a Principal. To make life easy this should NEVER return null. * * @param p the principal to check. * @return the list of attribute values that matched this role, or an empty collection if they don't. */ @SuppressWarnings("unchecked") private Collection<String> getRoleCollection(final Principal p) { if (!(p instanceof AttributePrincipal)) { return Collections.emptyList(); } final Object attributes = ((AttributePrincipal) p).getAttributes().get(this.roleAttributeName); if (attributes == null) { return Collections.emptyList(); } if (attributes instanceof Collection<?>) { return (Collection<String>) attributes; } return Arrays.asList(attributes.toString()); } }
/** * Retrieves the attributes for a Principal. To make life easy this should NEVER return null. * * @param p the principal to check. * @return the list of attribute values that matched this role, or an empty collection if they don't. */ @SuppressWarnings("unchecked") private Collection<String> getRoleCollection(final Principal p) { if (!(p instanceof AttributePrincipal)) { return Collections.emptyList(); } final Object attributes = ((AttributePrincipal) p).getAttributes().get(this.roleAttributeName); if (attributes == null) { return Collections.emptyList(); } if (attributes instanceof Collection<?>) { return (Collection<String>) attributes; } return Arrays.asList(attributes.toString()); } }
protected UserDetails loadUserDetails(Assertion assertion) { String username = assertion.getPrincipal().getName(); if (!StringUtils.hasText(username)) { throw new UsernameNotFoundException("Unable to retrieve username from CAS assertion"); } Map<String, Object> principalAttributes = assertion.getPrincipal().getAttributes(); List<GrantedAuthority> authorities = Arrays .stream(attributes) .map(principalAttributes::get) .filter(Objects::nonNull) .flatMap(v -> (v instanceof Collection) ? ((Collection<?>) v).stream() : Stream.of(v)) .map(v -> toUppercase ? v.toString().toUpperCase() : v.toString()) .map(r -> r.replaceFirst("^ROLE_", "")) .map(r -> new SimpleGrantedAuthority("ROLE_" + r)) .collect(Collectors.toList()); authorities.addAll(defaultGrantedAuthorities); return new User(username, NON_EXISTENT_PASSWORD_VALUE, authorities); } }
@SuppressWarnings("unchecked") @Override protected UserDetails loadUserDetails(final Assertion assertion) { final List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (final String attribute : this.attributes) { final Object value = assertion.getPrincipal().getAttributes().get(attribute); if (value == null) { continue; } if (value instanceof List) { final List list = (List) value; for (final Object o : list) { grantedAuthorities.add(new SimpleGrantedAuthority( this.convertToUpperCase ? o.toString().toUpperCase() : o .toString())); } } else { grantedAuthorities.add(new SimpleGrantedAuthority( this.convertToUpperCase ? value.toString().toUpperCase() : value .toString())); } } return new User(assertion.getPrincipal().getName(), NON_EXISTENT_PASSWORD_VALUE, true, true, true, true, grantedAuthorities); }
@SuppressWarnings("unchecked") @Override protected UserDetails loadUserDetails(final Assertion assertion) { final List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (final String attribute : this.attributes) { final Object value = assertion.getPrincipal().getAttributes().get(attribute); if (value == null) { continue; } if (value instanceof List) { final List list = (List) value; for (final Object o : list) { grantedAuthorities.add(new SimpleGrantedAuthority( this.convertToUpperCase ? o.toString().toUpperCase() : o .toString())); } } else { grantedAuthorities.add(new SimpleGrantedAuthority( this.convertToUpperCase ? value.toString().toUpperCase() : value .toString())); } } return new User(assertion.getPrincipal().getName(), NON_EXISTENT_PASSWORD_VALUE, true, true, true, true, grantedAuthorities); }
/** * Log cas validation assertion. * * @param assertion the assertion */ protected void logCasValidationAssertion(final Assertion assertion) { LOGGER.debug("CAS Assertion Valid: [{}]", assertion.isValid()); LOGGER.debug("CAS Assertion Principal: [{}]", assertion.getPrincipal().getName()); LOGGER.debug("CAS Assertion authentication Date: [{}]", assertion.getAuthenticationDate()); LOGGER.debug("CAS Assertion ValidFrom Date: [{}]", assertion.getValidFromDate()); LOGGER.debug("CAS Assertion ValidUntil Date: [{}]", assertion.getValidUntilDate()); LOGGER.debug("CAS Assertion Attributes: [{}]", assertion.getAttributes()); LOGGER.debug("CAS Assertion Principal Attributes: [{}]", assertion.getPrincipal().getAttributes()); }
public boolean isUserInRole(final String role) { if (CommonUtils.isBlank(role)) { log.debug("No valid role provided. Returning false."); return false; } if (this.principal == null) { log.debug("No Principal in Request. Returning false."); return false; } if (CommonUtils.isBlank(roleAttribute)) { log.debug("No Role Attribute Configured. Returning false."); return false; } final Object value = this.principal.getAttributes().get(roleAttribute); if (value instanceof Collection) { for (final Iterator iter = ((Collection) value).iterator(); iter.hasNext();) { if (rolesEqual(role, iter.next())) { log.debug("User [" + getRemoteUser() + "] is in role [" + role + "]: " + true); return true; } } } final boolean isMember = rolesEqual(role, value); log.debug("User [" + getRemoteUser() + "] is in role [" + role + "]: " + isMember); return isMember; }
public boolean isUserInRole(final String role) { if (CommonUtils.isBlank(role)) { logger.debug("No valid role provided. Returning false."); return false; } if (this.principal == null) { logger.debug("No Principal in Request. Returning false."); return false; } if (CommonUtils.isBlank(roleAttribute)) { logger.debug("No Role Attribute Configured. Returning false."); return false; } final Object value = this.principal.getAttributes().get(roleAttribute); if (value instanceof Collection<?>) { for (final Object o : (Collection<?>) value) { if (rolesEqual(role, o)) { logger.debug("User [{}] is in role [{}]: true", getRemoteUser(), role); return true; } } } final boolean isMember = rolesEqual(role, value); logger.debug("User [{}] is in role [{}]: {}", getRemoteUser(), role, isMember); return isMember; }
public User fetchLogin() { User user = new User(); Assertion assertion = AssertionHolder.getAssertion(); AttributePrincipal principal = assertion.getPrincipal(); String infoSnapshot = principal.getName(); String[] info = infoSnapshot.split("\\|"); user.setName(info[0]); try { Map<String, Object> attributes = principal.getAttributes(); user.setNumber(Long.valueOf((String) attributes.get("UserNum"))); user.setChineseName(URLDecoder.decode((String) attributes.get("UserName"), "utf-8")); user.setDepartmentName(URLDecoder.decode((String) attributes.get("DeptName"), "utf-8")); user.setDepartmentStruction(URLDecoder.decode((String) attributes.get("DeptFullName"), "utf-8")); user.setEmail(URLDecoder.decode((String) attributes.get("UserEmail"), "utf-8")); user.setMobile((String) attributes.get("UserMobile")); } catch (NumberFormatException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return user; }
private AttributeStatement buildAttributeStatement(final Object casAssertion, final RequestAbstractType authnRequest, final SamlRegisteredService service, final SamlRegisteredServiceServiceProviderMetadataFacade adaptor, final MessageContext messageContext) throws SamlException { val assertion = Assertion.class.cast(casAssertion); val attributes = new HashMap<String, Object>(assertion.getAttributes()); attributes.putAll(assertion.getPrincipal().getAttributes()); val encodedAttrs = this.samlAttributeEncoder.encodeAttributes(attributes, service); val resp = samlIdPProperties.getResponse(); val nameFormats = new HashMap<String, String>(resp.configureAttributeNameFormats()); nameFormats.putAll(service.getAttributeNameFormats()); return newAttributeStatement(encodedAttrs, service.getAttributeFriendlyNames(), nameFormats, resp.getDefaultAttributeNameFormat(), new SamlProfileSamlRegisteredServiceAttributeBuilder(service, adaptor, messageContext, samlObjectEncrypter)); } }
@Override @SneakyThrows public String build(final String serviceTicketId, final Service service) { val assertion = this.ticketValidator.validate(serviceTicketId, service.getId()); val attributes = new HashMap<String, Object>(assertion.getAttributes()); attributes.putAll(assertion.getPrincipal().getAttributes()); val validUntilDate = FunctionUtils.doIf( assertion.getValidUntilDate() != null, assertion::getValidUntilDate, () -> { val dt = ZonedDateTime.now().plusSeconds(expirationPolicy.getTimeToLive()); return DateTimeUtils.dateOf(dt); }) .get(); return buildJwt(serviceTicketId, service.getId(), assertion.getAuthenticationDate(), assertion.getPrincipal().getName(), validUntilDate, attributes); }
@Test public void testSuccessfulJsonResponse() throws Exception { final String RESPONSE = "{ " + "\"serviceResponse\" : { " + "\"authenticationSuccess\" : { " + "\"user\" : \"casuser\", " + "\"proxyGrantingTicket\" : \"PGTIOU-84678-8a9d\" ," + "\"attributes\" : { " + "\"cn\" : [ \"Name\" ] " + '}' + '}' + '}' + '}'; server.content = RESPONSE.getBytes(server.encoding); final Assertion assertion = ticketValidator.validate("test", "test"); Assert.assertEquals(assertion.getPrincipal().getName(), "casuser"); Assert.assertTrue(assertion.getPrincipal().getAttributes().containsKey("cn")); }
@Test public void testGetInlinedAttributes() throws TicketValidationException, UnsupportedEncodingException { final String USERNAME = "username"; final String PGTIOU = "testPgtIou"; final String RESPONSE = "<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'><cas:authenticationSuccess><cas:user>" + USERNAME + "</cas:user><cas:proxyGrantingTicket>" + PGTIOU + "</cas:proxyGrantingTicket><cas:attributes><cas:attribute name=\"password\" value=\"test\"/><cas:attribute name=\"eduPersonId\" value=\"id\"/><cas:attribute name=\"longAttribute\" value=\"test1 test\"/><cas:attribute name=\"multivaluedAttribute\" value=\"value1\"/><cas:attribute name=\"multivaluedAttribute\" value=\"value2\"/></cas:attributes></cas:authenticationSuccess></cas:serviceResponse>"; server.content = RESPONSE.getBytes(server.encoding); final Assertion assertion = this.ticketValidator.validate("test", "test"); assertEquals(USERNAME, assertion.getPrincipal().getName()); assertEquals("test", assertion.getPrincipal().getAttributes().get("password")); assertEquals("id", assertion.getPrincipal().getAttributes().get("eduPersonId")); assertEquals("test1\n\ntest", assertion.getPrincipal().getAttributes().get("longAttribute")); try { List<?> multivalued = (List<?>) assertion.getPrincipal().getAttributes().get("multivaluedAttribute"); assertArrayEquals(new String[] { "value1", "value2" }, multivalued.toArray()); } catch (Exception e) { fail("'multivaluedAttribute' attribute expected as List<Object> object."); } //assertEquals(PGT, assertion.getProxyGrantingTicketId()); }
@Test public void testGetAttributes() throws TicketValidationException, UnsupportedEncodingException { final String USERNAME = "username"; final String PGTIOU = "testPgtIou"; final String RESPONSE = "<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'><cas:authenticationSuccess><cas:user>" + USERNAME + "</cas:user><cas:proxyGrantingTicket>" + PGTIOU + "</cas:proxyGrantingTicket><cas:attributes><cas:password>test</cas:password><cas:eduPersonId>id</cas:eduPersonId><cas:longAttribute>test1\n\ntest</cas:longAttribute><cas:multivaluedAttribute>value1</cas:multivaluedAttribute><cas:multivaluedAttribute>value2</cas:multivaluedAttribute></cas:attributes></cas:authenticationSuccess></cas:serviceResponse>"; server.content = RESPONSE.getBytes(server.encoding); final Assertion assertion = this.ticketValidator.validate("test", "test"); assertEquals(USERNAME, assertion.getPrincipal().getName()); assertEquals("test", assertion.getPrincipal().getAttributes().get("password")); assertEquals("id", assertion.getPrincipal().getAttributes().get("eduPersonId")); assertEquals("test1\n\ntest", assertion.getPrincipal().getAttributes().get("longAttribute")); try { List<?> multivalued = (List<?>) assertion.getPrincipal().getAttributes().get("multivaluedAttribute"); assertArrayEquals(new String[] { "value1", "value2" }, multivalued.toArray()); } catch (Exception e) { fail("'multivaluedAttribute' attribute expected as List<Object> object."); } //assertEquals(PGT, assertion.getProxyGrantingTicketId()); }
@Test public void testGetAttributes() throws TicketValidationException, UnsupportedEncodingException { final String USERNAME = "username"; final String PGTIOU = "testPgtIou"; final String RESPONSE = "<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'><cas:authenticationSuccess><cas:user>" + USERNAME + "</cas:user><cas:proxyGrantingTicket>" + PGTIOU + "</cas:proxyGrantingTicket><cas:attributes><cas:password>test</cas:password><cas:eduPersonId>id</cas:eduPersonId><cas:longAttribute>test1\n\ntest</cas:longAttribute><cas:multivaluedAttribute>value1</cas:multivaluedAttribute><cas:multivaluedAttribute>value2</cas:multivaluedAttribute></cas:attributes></cas:authenticationSuccess></cas:serviceResponse>"; server.content = RESPONSE.getBytes(server.encoding); final Assertion assertion = this.ticketValidator.validate("test", "test"); assertEquals(USERNAME, assertion.getPrincipal().getName()); assertEquals("test", assertion.getPrincipal().getAttributes().get("password")); assertEquals("id", assertion.getPrincipal().getAttributes().get("eduPersonId")); assertEquals("test1\n\ntest", assertion.getPrincipal().getAttributes().get("longAttribute")); try { List<?> multivalued = (List<?>) assertion.getPrincipal().getAttributes().get("multivaluedAttribute"); assertArrayEquals(new String[] { "value1", "value2" }, multivalued.toArray()); } catch (Exception e) { fail("'multivaluedAttribute' attribute expected as List<Object> object."); } //assertEquals(PGT, assertion.getProxyGrantingTicketId()); }