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);
}
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());
}
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;
}
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());
}
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);
}
Aggregations