Search in sources :

Example 1 with ExtendedLdapUserDetails

use of org.cloudfoundry.identity.uaa.provider.ldap.ExtendedLdapUserDetails in project uaa by cloudfoundry.

the class InvitationsController method acceptLdapInvitation.

@RequestMapping(value = "/accept_enterprise.do", method = POST)
public String acceptLdapInvitation(@RequestParam("enterprise_username") String username, @RequestParam("enterprise_password") String password, @RequestParam("enterprise_email") String email, @RequestParam("code") String code, Model model, HttpServletResponse response) {
    ExpiringCode expiringCode = expiringCodeStore.retrieveCode(code, IdentityZoneHolder.get().getId());
    if (expiringCode == null) {
        return handleUnprocessableEntity(model, response, "error_message_code", "code_expired", "invitations/accept_enterprise.do");
    }
    String newCode = expiringCodeStore.generateCode(expiringCode.getData(), new Timestamp(System.currentTimeMillis() + (1000 * 60 * 10)), null, IdentityZoneHolder.get().getId()).getCode();
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
    AuthenticationManager authenticationManager = null;
    IdentityProvider ldapProvider = null;
    try {
        ldapProvider = identityProviderProvisioning.retrieveByOrigin(OriginKeys.LDAP, IdentityZoneHolder.get().getId());
        zoneAwareAuthenticationManager.getLdapAuthenticationManager(IdentityZoneHolder.get(), ldapProvider).getLdapAuthenticationManager();
        authenticationManager = zoneAwareAuthenticationManager.getLdapAuthenticationManager(IdentityZoneHolder.get(), ldapProvider).getLdapManagerActual();
    } catch (EmptyResultDataAccessException e) {
        // ldap provider was not available
        return handleUnprocessableEntity(model, response, "error_message_code", "no_suitable_idp", "invitations/accept_invite");
    } catch (Exception x) {
        logger.error("Unable to retrieve LDAP config.", x);
        return handleUnprocessableEntity(model, response, "error_message_code", "no_suitable_idp", "invitations/accept_invite");
    }
    Authentication authentication;
    try {
        authentication = authenticationManager.authenticate(token);
        Map<String, String> data = JsonUtils.readValue(expiringCode.getData(), new TypeReference<>() {
        });
        ScimUser user = userProvisioning.retrieve(data.get("user_id"), IdentityZoneHolder.get().getId());
        if (!user.getPrimaryEmail().equalsIgnoreCase(((ExtendedLdapUserDetails) authentication.getPrincipal()).getEmailAddress())) {
            model.addAttribute("email", data.get("email"));
            model.addAttribute("provider", OriginKeys.LDAP);
            model.addAttribute("code", expiringCodeStore.generateCode(expiringCode.getData(), new Timestamp(System.currentTimeMillis() + (10 * 60 * 1000)), null, IdentityZoneHolder.get().getId()).getCode());
            return handleUnprocessableEntity(model, response, "error_message", "invite.email_mismatch", "invitations/accept_invite");
        }
        if (authentication.isAuthenticated()) {
            // change username from email to username
            user.setUserName(((ExtendedLdapUserDetails) authentication.getPrincipal()).getUsername());
            userProvisioning.update(user.getId(), user, IdentityZoneHolder.get().getId());
            zoneAwareAuthenticationManager.getLdapAuthenticationManager(IdentityZoneHolder.get(), ldapProvider).authenticate(token);
            AcceptedInvitation accept = invitationsService.acceptInvitation(newCode, "");
            return "redirect:" + "/login?success=invite_accepted&form_redirect_uri=" + URLEncoder.encode(accept.getRedirectUri());
        } else {
            return handleUnprocessableEntity(model, response, "error_message", "not authenticated", "invitations/accept_invite");
        }
    } catch (AuthenticationException x) {
        return handleUnprocessableEntity(model, response, "error_message", x.getMessage(), "invitations/accept_invite");
    } catch (Exception x) {
        logger.error("Unable to authenticate against LDAP", x);
        model.addAttribute("ldap", true);
        model.addAttribute("email", email);
        return handleUnprocessableEntity(model, response, "error_message", "bad_credentials", "invitations/accept_invite");
    }
}
Also used : ScimUser(org.cloudfoundry.identity.uaa.scim.ScimUser) AuthenticationException(org.springframework.ldap.AuthenticationException) ExtendedLdapUserDetails(org.cloudfoundry.identity.uaa.provider.ldap.ExtendedLdapUserDetails) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) IdentityProvider(org.cloudfoundry.identity.uaa.provider.IdentityProvider) Timestamp(java.sql.Timestamp) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) AuthenticationException(org.springframework.ldap.AuthenticationException) InvalidPasswordException(org.cloudfoundry.identity.uaa.scim.exception.InvalidPasswordException) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) DynamicZoneAwareAuthenticationManager(org.cloudfoundry.identity.uaa.authentication.manager.DynamicZoneAwareAuthenticationManager) AuthenticationManager(org.springframework.security.authentication.AuthenticationManager) ExpiringCode(org.cloudfoundry.identity.uaa.codestore.ExpiringCode) Authentication(org.springframework.security.core.Authentication) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 2 with ExtendedLdapUserDetails

use of org.cloudfoundry.identity.uaa.provider.ldap.ExtendedLdapUserDetails in project uaa by cloudfoundry.

the class InvitationsControllerTest method unverifiedLdapUser_acceptsInvite_byLoggingIn.

@Test
public void unverifiedLdapUser_acceptsInvite_byLoggingIn() throws Exception {
    Map<String, String> codeData = getInvitationsCode(LDAP);
    when(expiringCodeStore.retrieveCode("the_secret_code", IdentityZoneHolder.get().getId())).thenReturn(new ExpiringCode("code", new Timestamp(System.currentTimeMillis()), JsonUtils.writeValueAsString(codeData), null));
    when(expiringCodeStore.generateCode(anyString(), any(), eq(null), eq(IdentityZoneHolder.get().getId()))).thenReturn(new ExpiringCode("code", new Timestamp(System.currentTimeMillis()), JsonUtils.writeValueAsString(codeData), null));
    DynamicLdapAuthenticationManager ldapAuthenticationManager = mock(DynamicLdapAuthenticationManager.class);
    when(zoneAwareAuthenticationManager.getLdapAuthenticationManager(any(), any())).thenReturn(ldapAuthenticationManager);
    AuthenticationManager ldapActual = mock(AuthenticationManager.class);
    when(ldapAuthenticationManager.getLdapManagerActual()).thenReturn(ldapActual);
    Authentication auth = mock(Authentication.class);
    when(auth.isAuthenticated()).thenReturn(true);
    when(ldapActual.authenticate(any())).thenReturn(auth);
    ExtendedLdapUserDetails extendedLdapUserDetails = mock(ExtendedLdapUserDetails.class);
    when(auth.getPrincipal()).thenReturn(extendedLdapUserDetails);
    when(extendedLdapUserDetails.getEmailAddress()).thenReturn("user@example.com");
    when(extendedLdapUserDetails.getUsername()).thenReturn("test-ldap-user");
    ScimUser invitedUser = new ScimUser("user-id-001", "user@example.com", "g", "f");
    invitedUser.setPrimaryEmail("user@example.com");
    when(scimUserProvisioning.retrieve("user-id-001", IdentityZoneHolder.get().getId())).thenReturn(invitedUser);
    when(invitationsService.acceptInvitation(anyString(), anyString())).thenReturn(new AcceptedInvitation("blah.test.com", new ScimUser()));
    when(expiringCodeStore.generateCode(anyString(), any(), eq(null), eq(IdentityZoneHolder.get().getId()))).thenReturn(new ExpiringCode("code", new Timestamp(System.currentTimeMillis()), JsonUtils.writeValueAsString(codeData), null));
    mockMvc.perform(post("/invitations/accept_enterprise.do").param("enterprise_username", "test-ldap-user").param("enterprise_password", "password").param("enterprise_email", "email").param("code", "the_secret_code")).andExpect(redirectedUrl("/login?success=invite_accepted&form_redirect_uri=blah.test.com")).andReturn();
    verify(ldapActual).authenticate(any());
    ArgumentCaptor<ScimUser> userArgumentCaptor = ArgumentCaptor.forClass(ScimUser.class);
    verify(scimUserProvisioning).update(anyString(), userArgumentCaptor.capture(), eq(IdentityZoneHolder.get().getId()));
    ScimUser value = userArgumentCaptor.getValue();
    assertEquals("test-ldap-user", value.getUserName());
    assertEquals("user@example.com", value.getPrimaryEmail());
    verify(ldapAuthenticationManager).authenticate(any());
}
Also used : DynamicLdapAuthenticationManager(org.cloudfoundry.identity.uaa.authentication.manager.DynamicLdapAuthenticationManager) DynamicLdapAuthenticationManager(org.cloudfoundry.identity.uaa.authentication.manager.DynamicLdapAuthenticationManager) DynamicZoneAwareAuthenticationManager(org.cloudfoundry.identity.uaa.authentication.manager.DynamicZoneAwareAuthenticationManager) AuthenticationManager(org.springframework.security.authentication.AuthenticationManager) ScimUser(org.cloudfoundry.identity.uaa.scim.ScimUser) ExpiringCode(org.cloudfoundry.identity.uaa.codestore.ExpiringCode) Authentication(org.springframework.security.core.Authentication) ExtendedLdapUserDetails(org.cloudfoundry.identity.uaa.provider.ldap.ExtendedLdapUserDetails) Matchers.containsString(org.hamcrest.Matchers.containsString) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Timestamp(java.sql.Timestamp) Test(org.junit.Test)

Example 3 with ExtendedLdapUserDetails

use of org.cloudfoundry.identity.uaa.provider.ldap.ExtendedLdapUserDetails in project uaa by cloudfoundry.

the class InvitationsControllerTest method unverifiedLdapUser_acceptsInvite_byLoggingIn_whereEmailDoesNotMatchAuthenticatedEmail.

@Test
public void unverifiedLdapUser_acceptsInvite_byLoggingIn_whereEmailDoesNotMatchAuthenticatedEmail() throws Exception {
    Map<String, String> codeData = getInvitationsCode(LDAP);
    when(expiringCodeStore.retrieveCode("the_secret_code", IdentityZoneHolder.get().getId())).thenReturn(new ExpiringCode("code", new Timestamp(System.currentTimeMillis()), JsonUtils.writeValueAsString(codeData), null));
    DynamicLdapAuthenticationManager ldapAuthenticationManager = mock(DynamicLdapAuthenticationManager.class);
    when(zoneAwareAuthenticationManager.getLdapAuthenticationManager(any(), any())).thenReturn(ldapAuthenticationManager);
    AuthenticationManager ldapActual = mock(AuthenticationManager.class);
    when(ldapAuthenticationManager.getLdapManagerActual()).thenReturn(ldapActual);
    Authentication auth = mock(Authentication.class);
    when(ldapActual.authenticate(any())).thenReturn(auth);
    ExtendedLdapUserDetails extendedLdapUserDetails = mock(ExtendedLdapUserDetails.class);
    when(auth.getPrincipal()).thenReturn(extendedLdapUserDetails);
    when(extendedLdapUserDetails.getEmailAddress()).thenReturn("different-email@example.com");
    ScimUser invitedUser = new ScimUser("user-id-001", "user@example.com", "g", "f");
    invitedUser.setPrimaryEmail("user@example.com");
    when(scimUserProvisioning.retrieve("user-id-001", IdentityZoneHolder.get().getId())).thenReturn(invitedUser);
    when(expiringCodeStore.generateCode(anyString(), any(), eq(null), eq(IdentityZoneHolder.get().getId()))).thenReturn(new ExpiringCode("code", new Timestamp(System.currentTimeMillis()), JsonUtils.writeValueAsString(codeData), null));
    mockMvc.perform(post("/invitations/accept_enterprise.do").param("enterprise_username", "test-ldap-user").param("enterprise_password", "password").param("enterprise_email", "email").param("code", "the_secret_code")).andExpect(status().isUnprocessableEntity()).andExpect(view().name("invitations/accept_invite")).andExpect(content().string(containsString("Email: " + "user@example.com"))).andExpect(content().string(containsString("Sign in with enterprise credentials:"))).andExpect(content().string(containsString("username"))).andExpect(model().attribute("code", "code")).andExpect(model().attribute("error_message", "invite.email_mismatch")).andReturn();
    verify(ldapActual).authenticate(any());
}
Also used : DynamicLdapAuthenticationManager(org.cloudfoundry.identity.uaa.authentication.manager.DynamicLdapAuthenticationManager) DynamicLdapAuthenticationManager(org.cloudfoundry.identity.uaa.authentication.manager.DynamicLdapAuthenticationManager) DynamicZoneAwareAuthenticationManager(org.cloudfoundry.identity.uaa.authentication.manager.DynamicZoneAwareAuthenticationManager) AuthenticationManager(org.springframework.security.authentication.AuthenticationManager) ScimUser(org.cloudfoundry.identity.uaa.scim.ScimUser) ExpiringCode(org.cloudfoundry.identity.uaa.codestore.ExpiringCode) Authentication(org.springframework.security.core.Authentication) ExtendedLdapUserDetails(org.cloudfoundry.identity.uaa.provider.ldap.ExtendedLdapUserDetails) Matchers.containsString(org.hamcrest.Matchers.containsString) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Timestamp(java.sql.Timestamp) Test(org.junit.Test)

Example 4 with ExtendedLdapUserDetails

use of org.cloudfoundry.identity.uaa.provider.ldap.ExtendedLdapUserDetails in project uaa by cloudfoundry.

the class LdapLoginAuthenticationManager method getUserAttributes.

@Override
protected MultiValueMap<String, String> getUserAttributes(UserDetails request) {
    MultiValueMap<String, String> result = super.getUserAttributes(request);
    logger.debug(String.format("Mapping custom attributes for origin:%s and zone:%s", getOrigin(), IdentityZoneHolder.get().getId()));
    if (getProviderProvisioning() != null) {
        IdentityProvider provider = getProviderProvisioning().retrieveByOrigin(getOrigin(), IdentityZoneHolder.get().getId());
        if (request instanceof ExtendedLdapUserDetails) {
            ExtendedLdapUserDetails ldapDetails = ((ExtendedLdapUserDetails) request);
            LdapIdentityProviderDefinition ldapIdentityProviderDefinition = ObjectUtils.castInstance(provider.getConfig(), LdapIdentityProviderDefinition.class);
            Map<String, Object> providerMappings = ldapIdentityProviderDefinition.getAttributeMappings();
            for (Map.Entry<String, Object> entry : providerMappings.entrySet()) {
                if (entry.getKey().startsWith(USER_ATTRIBUTE_PREFIX) && entry.getValue() != null) {
                    String key = entry.getKey().substring(USER_ATTRIBUTE_PREFIX.length());
                    String[] values = ldapDetails.getAttribute((String) entry.getValue(), false);
                    if (values != null && values.length > 0) {
                        result.put(key, Arrays.asList(values));
                        logger.debug(String.format("Mappcustom attribute key:%s and value:%s", key, result.get(key)));
                    }
                }
            }
        }
    } else {
        logger.debug(String.format("Did not find custom attribute configuration for origin:%s and zone:%s", getOrigin(), IdentityZoneHolder.get().getId()));
    }
    return result;
}
Also used : ExtendedLdapUserDetails(org.cloudfoundry.identity.uaa.provider.ldap.ExtendedLdapUserDetails) IdentityProvider(org.cloudfoundry.identity.uaa.provider.IdentityProvider) Map(java.util.Map) MultiValueMap(org.springframework.util.MultiValueMap) LdapIdentityProviderDefinition(org.cloudfoundry.identity.uaa.provider.LdapIdentityProviderDefinition)

Aggregations

ExtendedLdapUserDetails (org.cloudfoundry.identity.uaa.provider.ldap.ExtendedLdapUserDetails)4 Timestamp (java.sql.Timestamp)3 DynamicZoneAwareAuthenticationManager (org.cloudfoundry.identity.uaa.authentication.manager.DynamicZoneAwareAuthenticationManager)3 ExpiringCode (org.cloudfoundry.identity.uaa.codestore.ExpiringCode)3 ScimUser (org.cloudfoundry.identity.uaa.scim.ScimUser)3 AuthenticationManager (org.springframework.security.authentication.AuthenticationManager)3 Authentication (org.springframework.security.core.Authentication)3 DynamicLdapAuthenticationManager (org.cloudfoundry.identity.uaa.authentication.manager.DynamicLdapAuthenticationManager)2 IdentityProvider (org.cloudfoundry.identity.uaa.provider.IdentityProvider)2 Matchers.containsString (org.hamcrest.Matchers.containsString)2 Test (org.junit.Test)2 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)2 Map (java.util.Map)1 LdapIdentityProviderDefinition (org.cloudfoundry.identity.uaa.provider.LdapIdentityProviderDefinition)1 InvalidPasswordException (org.cloudfoundry.identity.uaa.scim.exception.InvalidPasswordException)1 EmptyResultDataAccessException (org.springframework.dao.EmptyResultDataAccessException)1 AuthenticationException (org.springframework.ldap.AuthenticationException)1 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)1 MultiValueMap (org.springframework.util.MultiValueMap)1 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)1