Search in sources :

Example 1 with IdentityProviderAuthenticationFailureEvent

use of org.cloudfoundry.identity.uaa.authentication.event.IdentityProviderAuthenticationFailureEvent in project uaa by cloudfoundry.

the class PasswordGrantAuthenticationManagerTest method testOIDCPasswordGrantInvalidLogin.

@Test
void testOIDCPasswordGrantInvalidLogin() {
    UaaLoginHint loginHint = mock(UaaLoginHint.class);
    when(loginHint.getOrigin()).thenReturn("oidcprovider");
    Authentication auth = mock(Authentication.class);
    when(auth.getPrincipal()).thenReturn("marissa");
    when(auth.getCredentials()).thenReturn("koala1");
    when(zoneAwareAuthzAuthenticationManager.extractLoginHint(auth)).thenReturn(loginHint);
    RestTemplate rt = mock(RestTemplate.class);
    when(restTemplateConfig.nonTrustingRestTemplate()).thenReturn(rt);
    ResponseEntity<Map<String, String>> response = mock(ResponseEntity.class);
    when(response.hasBody()).thenReturn(true);
    when(response.getBody()).thenReturn(Collections.singletonMap("id_token", "mytoken"));
    HttpClientErrorException exception = mock(HttpClientErrorException.class);
    when(rt.exchange(anyString(), any(HttpMethod.class), any(HttpEntity.class), any(ParameterizedTypeReference.class))).thenThrow(exception);
    try {
        instance.authenticate(auth);
        fail("No Exception thrown.");
    } catch (BadCredentialsException ignored) {
    }
    ArgumentCaptor<AbstractUaaEvent> eventArgumentCaptor = ArgumentCaptor.forClass(AbstractUaaEvent.class);
    verify(eventPublisher, times(1)).publishEvent(eventArgumentCaptor.capture());
    assertEquals(1, eventArgumentCaptor.getAllValues().size());
    assertTrue(eventArgumentCaptor.getValue() instanceof IdentityProviderAuthenticationFailureEvent);
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) HttpEntity(org.springframework.http.HttpEntity) IdentityProviderAuthenticationFailureEvent(org.cloudfoundry.identity.uaa.authentication.event.IdentityProviderAuthenticationFailureEvent) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) UaaLoginHint(org.cloudfoundry.identity.uaa.authentication.UaaLoginHint) Authentication(org.springframework.security.core.Authentication) ParameterizedTypeReference(org.springframework.core.ParameterizedTypeReference) RestTemplate(org.springframework.web.client.RestTemplate) AbstractUaaEvent(org.cloudfoundry.identity.uaa.audit.event.AbstractUaaEvent) Map(java.util.Map) HashMap(java.util.HashMap) MultiValueMap(org.springframework.util.MultiValueMap) HttpMethod(org.springframework.http.HttpMethod) Test(org.junit.jupiter.api.Test)

Example 2 with IdentityProviderAuthenticationFailureEvent

use of org.cloudfoundry.identity.uaa.authentication.event.IdentityProviderAuthenticationFailureEvent in project uaa by cloudfoundry.

the class AbstractLdapMockMvcTest method testLogin.

@Test
void testLogin() throws Exception {
    getMockMvc().perform(get("/login").header(HOST, host)).andExpect(status().isOk()).andExpect(view().name("login")).andExpect(model().attributeDoesNotExist("saml"));
    getMockMvc().perform(post("/login.do").accept(TEXT_HTML_VALUE).header(HOST, host).with(cookieCsrf()).param("username", "marissa").param("password", "koaladsada")).andExpect(status().isFound()).andExpect(unauthenticated()).andExpect(redirectedUrl("/login?error=login_failure"));
    ArgumentCaptor<AbstractUaaEvent> captor = ArgumentCaptor.forClass(AbstractUaaEvent.class);
    verify(listener, atLeast(5)).onApplicationEvent(captor.capture());
    List<AbstractUaaEvent> allValues = captor.getAllValues();
    assertThat(allValues.get(5), instanceOf(IdentityProviderAuthenticationFailureEvent.class));
    IdentityProviderAuthenticationFailureEvent event = (IdentityProviderAuthenticationFailureEvent) allValues.get(5);
    assertEquals("marissa", event.getUsername());
    assertEquals(OriginKeys.LDAP, event.getAuthenticationType());
    testLogger.reset();
    testSuccessfulLogin();
    assertThat(testLogger.getMessageCount(), is(5));
    String zoneId = zone.getZone().getIdentityZone().getId();
    ScimUser createdUser = jdbcScimUserProvisioning.retrieveAll(zoneId).stream().filter(dbUser -> dbUser.getUserName().equals("marissa2")).findFirst().get();
    String userCreatedLogMessage = testLogger.getFirstLogMessageOfType(AuditEventType.UserCreatedEvent);
    String expectedMessage = String.format("UserCreatedEvent ('[\"user_id=%s\",\"username=marissa2\"]'): principal=%s, origin=[caller=null], identityZoneId=[%s]", createdUser.getId(), createdUser.getId(), zoneId);
    assertThat(userCreatedLogMessage, is(expectedMessage));
    captor = ArgumentCaptor.forClass(AbstractUaaEvent.class);
    verify(listener, atLeast(5)).onApplicationEvent(captor.capture());
    allValues = captor.getAllValues();
    assertThat(allValues.get(13), instanceOf(IdentityProviderAuthenticationSuccessEvent.class));
    IdentityProviderAuthenticationSuccessEvent successEvent = (IdentityProviderAuthenticationSuccessEvent) allValues.get(13);
    assertEquals(OriginKeys.LDAP, successEvent.getAuthenticationType());
}
Also used : ScimUser(org.cloudfoundry.identity.uaa.scim.ScimUser) IdentityProviderAuthenticationSuccessEvent(org.cloudfoundry.identity.uaa.authentication.event.IdentityProviderAuthenticationSuccessEvent) IdentityProviderAuthenticationFailureEvent(org.cloudfoundry.identity.uaa.authentication.event.IdentityProviderAuthenticationFailureEvent) AbstractUaaEvent(org.cloudfoundry.identity.uaa.audit.event.AbstractUaaEvent) Test(org.junit.jupiter.api.Test)

Example 3 with IdentityProviderAuthenticationFailureEvent

use of org.cloudfoundry.identity.uaa.authentication.event.IdentityProviderAuthenticationFailureEvent in project uaa by cloudfoundry.

the class AuthzAuthenticationManager method authenticate.

@Override
public Authentication authenticate(Authentication req) throws AuthenticationException {
    logger.debug("Processing authentication request for " + req.getName());
    if (req.getCredentials() == null) {
        BadCredentialsException e = new BadCredentialsException("No password supplied");
        publish(new AuthenticationFailureBadCredentialsEvent(req, e));
        throw e;
    }
    UaaUser user = getUaaUser(req);
    if (user == null) {
        logger.debug("No user named '" + req.getName() + "' was found for origin:" + origin);
        publish(new UserNotFoundEvent(req, IdentityZoneHolder.getCurrentZoneId()));
    } else {
        if (!accountLoginPolicy.isAllowed(user, req)) {
            logger.warn("Login policy rejected authentication for " + user.getUsername() + ", " + user.getId() + ". Ignoring login request.");
            AuthenticationPolicyRejectionException e = new AuthenticationPolicyRejectionException("Your account has been locked because of too many failed attempts to login.");
            publish(new AuthenticationFailureLockedEvent(req, e));
            throw e;
        }
        boolean passwordMatches = ((CharSequence) req.getCredentials()).length() != 0 && encoder.matches((CharSequence) req.getCredentials(), user.getPassword());
        if (!passwordMatches) {
            logger.debug("Password did not match for user " + req.getName());
            publish(new IdentityProviderAuthenticationFailureEvent(req, req.getName(), OriginKeys.UAA, IdentityZoneHolder.getCurrentZoneId()));
            publish(new UserAuthenticationFailureEvent(user, req, IdentityZoneHolder.getCurrentZoneId()));
        } else {
            logger.debug("Password successfully matched for userId[" + user.getUsername() + "]:" + user.getId());
            boolean userMustBeVerified = !allowUnverifiedUsers || !user.isLegacyVerificationBehavior();
            if (userMustBeVerified && !user.isVerified()) {
                publish(new UnverifiedUserAuthenticationEvent(user, req, IdentityZoneHolder.getCurrentZoneId()));
                logger.debug("Account not verified: " + user.getId());
                throw new AccountNotVerifiedException("Account not verified");
            }
            UaaAuthentication uaaAuthentication = new UaaAuthentication(new UaaPrincipal(user), user.getAuthorities(), (UaaAuthenticationDetails) req.getDetails());
            uaaAuthentication.setAuthenticationMethods(Collections.singleton("pwd"));
            if (userMustUpdatePassword(user)) {
                logger.info("Password change required for user: " + user.getEmail());
                user.setPasswordChangeRequired(true);
                SessionUtils.setPasswordChangeRequired(httpSession, true);
            }
            publish(new IdentityProviderAuthenticationSuccessEvent(user, uaaAuthentication, OriginKeys.UAA, IdentityZoneHolder.getCurrentZoneId()));
            return uaaAuthentication;
        }
    }
    BadCredentialsException e = new BadCredentialsException("Bad credentials");
    publish(new AuthenticationFailureBadCredentialsEvent(req, e));
    throw e;
}
Also used : UserAuthenticationFailureEvent(org.cloudfoundry.identity.uaa.authentication.event.UserAuthenticationFailureEvent) IdentityProviderAuthenticationSuccessEvent(org.cloudfoundry.identity.uaa.authentication.event.IdentityProviderAuthenticationSuccessEvent) IdentityProviderAuthenticationFailureEvent(org.cloudfoundry.identity.uaa.authentication.event.IdentityProviderAuthenticationFailureEvent) AuthenticationFailureBadCredentialsEvent(org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) UnverifiedUserAuthenticationEvent(org.cloudfoundry.identity.uaa.authentication.event.UnverifiedUserAuthenticationEvent) UaaAuthentication(org.cloudfoundry.identity.uaa.authentication.UaaAuthentication) UaaPrincipal(org.cloudfoundry.identity.uaa.authentication.UaaPrincipal) AuthenticationFailureLockedEvent(org.springframework.security.authentication.event.AuthenticationFailureLockedEvent) UserNotFoundEvent(org.cloudfoundry.identity.uaa.authentication.event.UserNotFoundEvent) AuthenticationPolicyRejectionException(org.cloudfoundry.identity.uaa.authentication.AuthenticationPolicyRejectionException) UaaUser(org.cloudfoundry.identity.uaa.user.UaaUser) AccountNotVerifiedException(org.cloudfoundry.identity.uaa.authentication.AccountNotVerifiedException)

Example 4 with IdentityProviderAuthenticationFailureEvent

use of org.cloudfoundry.identity.uaa.authentication.event.IdentityProviderAuthenticationFailureEvent in project uaa by cloudfoundry.

the class AbstractLdapMockMvcTest method testAuthenticateFailure.

@Test
void testAuthenticateFailure() throws Exception {
    String username = "marissa3";
    String password = "ldapsadadasas";
    MockHttpServletRequestBuilder post = post("/authenticate").header(HOST, host).accept(MediaType.APPLICATION_JSON).param("username", username).param("password", password);
    getMockMvc().perform(post).andExpect(status().isUnauthorized());
    ArgumentCaptor<AbstractUaaEvent> captor = ArgumentCaptor.forClass(AbstractUaaEvent.class);
    verify(listener, atLeast(5)).onApplicationEvent(captor.capture());
    List<AbstractUaaEvent> allValues = captor.getAllValues();
    assertThat(allValues.get(4), instanceOf(IdentityProviderAuthenticationFailureEvent.class));
    IdentityProviderAuthenticationFailureEvent event = (IdentityProviderAuthenticationFailureEvent) allValues.get(4);
    assertEquals("marissa3", event.getUsername());
    assertEquals(OriginKeys.LDAP, event.getAuthenticationType());
}
Also used : MockHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder) IdentityProviderAuthenticationFailureEvent(org.cloudfoundry.identity.uaa.authentication.event.IdentityProviderAuthenticationFailureEvent) AbstractUaaEvent(org.cloudfoundry.identity.uaa.audit.event.AbstractUaaEvent) Test(org.junit.jupiter.api.Test)

Example 5 with IdentityProviderAuthenticationFailureEvent

use of org.cloudfoundry.identity.uaa.authentication.event.IdentityProviderAuthenticationFailureEvent in project uaa by cloudfoundry.

the class PasswordGrantAuthenticationManager method oidcPasswordGrant.

private Authentication oidcPasswordGrant(Authentication authentication, OIDCIdentityProviderDefinition config) {
    // Token per RestCall
    URL tokenUrl = config.getTokenUrl();
    String clientId = config.getRelyingPartyId();
    String clientSecret = config.getRelyingPartySecret();
    if (clientId == null || clientSecret == null) {
        throw new ProviderConfigurationException("External OpenID Connect provider configuration is missing relyingPartyId or relyingPartySecret.");
    }
    String userName = authentication.getPrincipal() instanceof String ? (String) authentication.getPrincipal() : null;
    String password = authentication.getCredentials() instanceof String ? (String) authentication.getCredentials() : null;
    if (userName == null || password == null) {
        throw new BadCredentialsException("Request is missing username or password.");
    }
    RestTemplate rt;
    if (config.isSkipSslValidation()) {
        rt = restTemplateConfig.trustingRestTemplate();
    } else {
        rt = restTemplateConfig.nonTrustingRestTemplate();
    }
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    String auth = clientId + ":" + clientSecret;
    headers.add("Authorization", "Basic " + Base64Utils.encodeToString(auth.getBytes()));
    if (config.isSetForwardHeader() && authentication.getDetails() != null && authentication.getDetails() instanceof UaaAuthenticationDetails) {
        UaaAuthenticationDetails details = (UaaAuthenticationDetails) authentication.getDetails();
        if (details.getOrigin() != null) {
            headers.add("X-Forwarded-For", details.getOrigin());
        }
    }
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("grant_type", GRANT_TYPE_PASSWORD);
    params.add("response_type", "id_token");
    params.add("username", userName);
    params.add("password", password);
    List<Prompt> prompts = config.getPrompts();
    List<String> promptsToInclude = new ArrayList<>();
    if (prompts != null) {
        for (Prompt prompt : prompts) {
            if ("username".equals(prompt.getName()) || "password".equals(prompt.getName()) || "passcode".equals(prompt.getName()))
                continue;
            promptsToInclude.add(prompt.getName());
        }
    }
    if (authentication.getDetails() instanceof UaaAuthenticationDetails) {
        UaaAuthenticationDetails details = (UaaAuthenticationDetails) authentication.getDetails();
        for (String prompt : promptsToInclude) {
            String[] values = details.getParameterMap().get(prompt);
            if (values == null || values.length != 1 || !StringUtils.hasText(values[0])) {
                // No single value given, skip this parameter
                continue;
            }
            params.add(prompt, values[0]);
        }
    }
    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
    String idToken = null;
    try {
        ResponseEntity<Map<String, String>> tokenResponse = rt.exchange(tokenUrl.toString(), HttpMethod.POST, request, new ParameterizedTypeReference<Map<String, String>>() {
        });
        if (tokenResponse.hasBody()) {
            Map<String, String> body = tokenResponse.getBody();
            idToken = body.get("id_token");
        }
    } catch (HttpClientErrorException e) {
        publish(new IdentityProviderAuthenticationFailureEvent(authentication, userName, OriginKeys.OIDC10, IdentityZoneHolder.getCurrentZoneId()));
        throw new BadCredentialsException(e.getResponseBodyAsString(), e);
    }
    if (idToken == null) {
        publish(new IdentityProviderAuthenticationFailureEvent(authentication, userName, OriginKeys.OIDC10, IdentityZoneHolder.getCurrentZoneId()));
        throw new BadCredentialsException("Could not obtain id_token from external OpenID Connect provider.");
    }
    ExternalOAuthCodeToken token = new ExternalOAuthCodeToken(null, null, null, idToken, null, null);
    return externalOAuthAuthenticationManager.authenticate(token);
}
Also used : ProviderConfigurationException(org.cloudfoundry.identity.uaa.authentication.ProviderConfigurationException) HttpHeaders(org.springframework.http.HttpHeaders) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) HttpEntity(org.springframework.http.HttpEntity) UaaAuthenticationDetails(org.cloudfoundry.identity.uaa.authentication.UaaAuthenticationDetails) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) IdentityProviderAuthenticationFailureEvent(org.cloudfoundry.identity.uaa.authentication.event.IdentityProviderAuthenticationFailureEvent) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) URL(java.net.URL) RestTemplate(org.springframework.web.client.RestTemplate) Prompt(org.cloudfoundry.identity.uaa.login.Prompt) ExternalOAuthCodeToken(org.cloudfoundry.identity.uaa.provider.oauth.ExternalOAuthCodeToken) MultiValueMap(org.springframework.util.MultiValueMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) MultiValueMap(org.springframework.util.MultiValueMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap)

Aggregations

IdentityProviderAuthenticationFailureEvent (org.cloudfoundry.identity.uaa.authentication.event.IdentityProviderAuthenticationFailureEvent)5 AbstractUaaEvent (org.cloudfoundry.identity.uaa.audit.event.AbstractUaaEvent)3 Test (org.junit.jupiter.api.Test)3 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)3 IdentityProviderAuthenticationSuccessEvent (org.cloudfoundry.identity.uaa.authentication.event.IdentityProviderAuthenticationSuccessEvent)2 HttpEntity (org.springframework.http.HttpEntity)2 MultiValueMap (org.springframework.util.MultiValueMap)2 HttpClientErrorException (org.springframework.web.client.HttpClientErrorException)2 RestTemplate (org.springframework.web.client.RestTemplate)2 URL (java.net.URL)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 AccountNotVerifiedException (org.cloudfoundry.identity.uaa.authentication.AccountNotVerifiedException)1 AuthenticationPolicyRejectionException (org.cloudfoundry.identity.uaa.authentication.AuthenticationPolicyRejectionException)1 ProviderConfigurationException (org.cloudfoundry.identity.uaa.authentication.ProviderConfigurationException)1 UaaAuthentication (org.cloudfoundry.identity.uaa.authentication.UaaAuthentication)1 UaaAuthenticationDetails (org.cloudfoundry.identity.uaa.authentication.UaaAuthenticationDetails)1 UaaLoginHint (org.cloudfoundry.identity.uaa.authentication.UaaLoginHint)1 UaaPrincipal (org.cloudfoundry.identity.uaa.authentication.UaaPrincipal)1 UnverifiedUserAuthenticationEvent (org.cloudfoundry.identity.uaa.authentication.event.UnverifiedUserAuthenticationEvent)1