@Override protected final HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential) throws GeneralSecurityException, PreventedException { if (users == null || users.isEmpty()) { throw new FailedLoginException("No user can be accepted because none is defined"); } final String username = credential.getUsername(); final String cachedPassword = this.users.get(username); if (cachedPassword == null) { logger.debug("{} was not found in the map.", username); throw new AccountNotFoundException(username + " not found in backing map."); } final String encodedPassword = this.getPasswordEncoder().encode(credential.getPassword()); if (!cachedPassword.equals(encodedPassword)) { throw new FailedLoginException(); } return createHandlerResult(credential, this.principalFactory.createPrincipal(username), null); }
/** * {@inheritDoc} **/ @Override protected final HandlerResult doAuthentication(final Credential credential) throws GeneralSecurityException, PreventedException { final UsernamePasswordCredential userPass = (UsernamePasswordCredential) credential; if (userPass.getUsername() == null) { throw new AccountNotFoundException("Username is null."); } final String transformedUsername= this.principalNameTransformer.transform(userPass.getUsername()); if (transformedUsername == null) { throw new AccountNotFoundException("Transformed username is null."); } userPass.setUsername(transformedUsername); return authenticateUsernamePasswordInternal(userPass); }
@Override protected final HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential) throws GeneralSecurityException, PreventedException { try { if (this.fileName == null || !this.fileName.exists()) { throw new FileNotFoundException("Filename does not exist"); } final String username = credential.getUsername(); final String passwordOnRecord = getPasswordOnRecord(username); if (StringUtils.isBlank(passwordOnRecord)) { throw new AccountNotFoundException(username + " not found in backing file."); } final String password = credential.getPassword(); if (StringUtils.isNotBlank(password) && this.getPasswordEncoder().encode(password).equals(passwordOnRecord)) { return createHandlerResult(credential, this.principalFactory.createPrincipal(username), null); } } catch (final IOException e) { throw new PreventedException("IO error reading backing file", e); } throw new FailedLoginException(); }
/** * {@inheritDoc} */ @Override protected final HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential) throws GeneralSecurityException, PreventedException { try { final String username = credential.getUsername(); final String passwordOnRecord = getPasswordOnRecord(username); if (StringUtils.isBlank(passwordOnRecord)) { throw new AccountNotFoundException(username + " not found in backing file."); } final String password = credential.getPassword(); if (StringUtils.isNotBlank(password) && this.getPasswordEncoder().encode(password).equals(passwordOnRecord)) { return createHandlerResult(credential, this.principalFactory.createPrincipal(username), null); } } catch (final IOException e) { throw new PreventedException("IO error reading backing file", e); } throw new FailedLoginException(); }
@Override protected HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential transformedCredential, final String originalPassword) throws GeneralSecurityException, PreventedException { try { if (this.fileName == null) { throw new FileNotFoundException("Filename does not exist"); } final String username = transformedCredential.getUsername(); final String passwordOnRecord = getPasswordOnRecord(username); if (StringUtils.isBlank(passwordOnRecord)) { throw new AccountNotFoundException(username + " not found in backing file."); } if (matches(originalPassword, passwordOnRecord)) { return createHandlerResult(transformedCredential, this.principalFactory.createPrincipal(username), null); } } catch (final IOException e) { throw new PreventedException("IO error reading backing file", e); } throw new FailedLoginException(); }
@Override protected HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential c, final String originalPassword) throws GeneralSecurityException, PreventedException { try { final UsernamePasswordCredential creds = new UsernamePasswordCredential(c.getUsername(), c.getPassword()); final ResponseEntity<SimplePrincipal> authenticationResponse = api.authenticate(creds); if (authenticationResponse.getStatusCode() == HttpStatus.OK) { final SimplePrincipal principalFromRest = authenticationResponse.getBody(); if (principalFromRest == null || StringUtils.isBlank(principalFromRest.getId())) { throw new FailedLoginException("Could not determine authentication response from rest endpoint for " + c.getUsername()); } return createHandlerResult(c, this.principalFactory.createPrincipal(principalFromRest.getId(), principalFromRest.getAttributes()), new ArrayList<>()); } } catch (final HttpClientErrorException e) { if (e.getStatusCode() == HttpStatus.FORBIDDEN) { throw new AccountDisabledException("Could not authenticate forbidden account for " + c.getUsername()); } if (e.getStatusCode() == HttpStatus.UNAUTHORIZED) { throw new FailedLoginException("Could not authenticate account for " + c.getUsername()); } if (e.getStatusCode() == HttpStatus.NOT_FOUND) { throw new AccountNotFoundException("Could not locate account for " + c.getUsername()); } if (e.getStatusCode() == HttpStatus.LOCKED) { throw new AccountLockedException("Could not authenticate locked account for " + c.getUsername()); } if (e.getStatusCode() == HttpStatus.PRECONDITION_REQUIRED) { throw new AccountExpiredException("Could not authenticate expired account for " + c.getUsername()); } throw new FailedLoginException("Rest endpoint returned an unknown status code " + e.getStatusCode() + " for " + c.getUsername()); } throw new FailedLoginException("Rest endpoint returned an unknown response for " + c.getUsername()); }
@Override protected HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential, final String originalPassword) throws GeneralSecurityException, PreventedException { if (this.users == null || this.users.isEmpty()) { throw new FailedLoginException("No user can be accepted because none is defined"); } final String username = credential.getUsername(); final String cachedPassword = this.users.get(username); if (cachedPassword == null) { LOGGER.debug("[{}] was not found in the map.", username); throw new AccountNotFoundException(username + " not found in backing map."); } if (!StringUtils.equals(credential.getPassword(), cachedPassword)) { throw new FailedLoginException(); } final List<MessageDescriptor> list = new ArrayList<>(); return createHandlerResult(credential, this.principalFactory.createPrincipal(username), list); }
/** * Create handle authentication failure action. * * @param flow the flow */ protected void createHandleAuthenticationFailureAction(final Flow flow) { final ActionState handler = createActionState(flow, "handleAuthenticationFailure", createEvaluateAction("authenticationExceptionHandler")); createTransitionForState(handler, AccountDisabledException.class.getSimpleName(), CasWebflowConstants.VIEW_ID_ACCOUNT_DISABLED); createTransitionForState(handler, AccountLockedException.class.getSimpleName(), CasWebflowConstants.VIEW_ID_ACCOUNT_LOCKED); createTransitionForState(handler, AccountPasswordMustChangeException.class.getSimpleName(), CasWebflowConstants.VIEW_ID_MUST_CHANGE_PASSWORD); createTransitionForState(handler, CredentialExpiredException.class.getSimpleName(), CasWebflowConstants.VIEW_ID_EXPIRED_PASSWORD); createTransitionForState(handler, InvalidLoginLocationException.class.getSimpleName(), CasWebflowConstants.VIEW_ID_INVALID_WORKSTATION); createTransitionForState(handler, InvalidLoginTimeException.class.getSimpleName(), CasWebflowConstants.VIEW_ID_INVALID_AUTHENTICATION_HOURS); createTransitionForState(handler, FailedLoginException.class.getSimpleName(), CasWebflowConstants.STATE_ID_INIT_LOGIN_FORM); createTransitionForState(handler, AccountNotFoundException.class.getSimpleName(), CasWebflowConstants.STATE_ID_INIT_LOGIN_FORM); createTransitionForState(handler, UnauthorizedServiceForPrincipalException.class.getSimpleName(), CasWebflowConstants.STATE_ID_INIT_LOGIN_FORM); createTransitionForState(handler, PrincipalException.class.getSimpleName(), CasWebflowConstants.STATE_ID_INIT_LOGIN_FORM); createTransitionForState(handler, UnsatisfiedAuthenticationPolicyException.class.getSimpleName(), CasWebflowConstants.STATE_ID_INIT_LOGIN_FORM); createTransitionForState(handler, UnauthorizedAuthenticationException.class.getSimpleName(), CasWebflowConstants.VIEW_ID_AUTHENTICATION_BLOCKED); createStateDefaultTransition(handler, CasWebflowConstants.STATE_ID_INIT_LOGIN_FORM); }
/** {@inheritDoc} */ @Override protected final HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential) throws GeneralSecurityException, PreventedException { final String username = credential.getUsername(); final String cachedPassword = this.users.get(username); if (cachedPassword == null) { logger.debug("{} was not found in the map.", username); throw new AccountNotFoundException(username + " not found in backing map."); } final String encodedPassword = this.getPasswordEncoder().encode(credential.getPassword()); if (!cachedPassword.equals(encodedPassword)) { throw new FailedLoginException(); } return createHandlerResult(credential, new SimplePrincipal(username), null); }
/** {@inheritDoc} */ @Override protected final HandlerResult doAuthentication(final Credential credential) throws GeneralSecurityException, PreventedException { final UsernamePasswordCredential userPass = (UsernamePasswordCredential) credential; if (userPass.getUsername() == null) { throw new AccountNotFoundException("Username is null."); } final String transformedUsername= this.principalNameTransformer.transform(userPass.getUsername()); if (transformedUsername == null) { throw new AccountNotFoundException("Transformed username is null."); } userPass.setUsername(transformedUsername); return authenticateUsernamePasswordInternal(userPass); }
@Test public void testAuthenticateNotFound() throws Exception { if (!this.supportsNotFound) { return; } String username; for (final LdapEntry entry : this.testEntries) { username = getUsername(entry); try { this.handler.authenticate(new UsernamePasswordCredential("nobody", "badpassword")); fail("Should have thrown AccountNotFoundException."); } catch (final AccountNotFoundException e) { assertNotNull(e.getMessage()); } } }
/** {@inheritDoc} */ @Override protected final HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential) throws GeneralSecurityException, PreventedException { try { final String username = credential.getUsername(); final String passwordOnRecord = getPasswordOnRecord(username); if (passwordOnRecord == null) { throw new AccountNotFoundException(username + " not found in backing file."); } if (credential.getPassword() != null && this.getPasswordEncoder().encode(credential.getPassword()).equals(passwordOnRecord)) { return createHandlerResult(credential, new SimplePrincipal(username), null); } } catch (final IOException e) { throw new PreventedException("IO error reading backing file", e); } throw new FailedLoginException(); }
@Test public void handleAccountNotFoundExceptionByDefefault() { final AuthenticationExceptionHandler handler = new AuthenticationExceptionHandler(); final MessageContext ctx = mock(MessageContext.class); final Map<String, Class<? extends Exception>> map = new HashMap<>(); map.put("notFound", AccountNotFoundException.class); final String id = handler.handle(new AuthenticationException(map), ctx); assertEquals(id, AccountNotFoundException.class.getSimpleName()); }
@Test(expected = AccountNotFoundException.class) public void verifyFailsNullUserNameAndPassword() throws Exception { final UsernamePasswordCredential c = new UsernamePasswordCredential(); c.setUsername(null); c.setPassword(null); this.authenticationHandler.authenticate(c); }
@Test(expected = AccountNotFoundException.class) public void verifyFailsNullUserName() throws Exception { final UsernamePasswordCredential c = new UsernamePasswordCredential(); c.setUsername(null); c.setPassword("user"); this.authenticationHandler.authenticate(c); }
@Test(expected = AccountNotFoundException.class) public void verifyAuthenticationFailsToFindUser() throws Exception { final QueryDatabaseAuthenticationHandler q = new QueryDatabaseAuthenticationHandler(); q.setDataSource(this.dataSource); q.setSql(SQL); q.authenticateUsernamePasswordInternal( TestUtils.getCredentialsWithDifferentUsernameAndPassword("usernotfound", "psw1")); }
@Test(expected = AccountNotFoundException.class) public void verifyAuthenticationFailsToFindUser() throws Exception { final QueryAndEncodeDatabaseAuthenticationHandler q = new QueryAndEncodeDatabaseAuthenticationHandler(); q.setDataSource(dataSource); q.setAlgorithmName(ALG_NAME); q.setSql(buildSql()); q.authenticateUsernamePasswordInternal(TestUtils.getCredentialsWithSameUsernameAndPassword()); }
@Override protected TokenCredentials convertToPac4jCredentials(final BasicIdentifiableCredential casCredential) throws GeneralSecurityException, PreventedException { logger.debug("CAS credentials: {}", casCredential); final String id = this.principalNameTransformer.transform(casCredential.getId()); if (id == null) { throw new AccountNotFoundException("Id is null."); } final TokenCredentials credentials = new TokenCredentials(id, getClass().getSimpleName()); logger.debug("pac4j credentials: {}", credentials); return credentials; }
@Test(expected = AccountNotFoundException.class) public void verifyFailsUserNotInFileWithCommaSeparator() throws Exception { final UsernamePasswordCredential c = new UsernamePasswordCredential(); this.authenticationHandler.setFileName( new ClassPathResource("org/jasig/cas/adaptors/generic/authentication2.txt")); this.authenticationHandler.setSeparator(","); c.setUsername("fds"); c.setPassword("rutgers"); this.authenticationHandler.authenticate(c); }
@Test(expected = AccountNotFoundException.class) public void verifyPassesNullUserName() throws Exception { final UsernamePasswordCredential c = new UsernamePasswordCredential(); c.setUsername(null); c.setPassword("user"); this.authenticationHandler.authenticate(c); }
@Test(expected = AccountNotFoundException.class) public void verifyFailsUserNotInFileWithDefaultSeparator() throws Exception { final UsernamePasswordCredential c = new UsernamePasswordCredential(); c.setUsername("fds"); c.setPassword("rutgers"); this.authenticationHandler.authenticate(c); }
/** * {@inheritDoc} * Attempts to authenticate the received credentials using the Yubico cloud validation platform. * In this implementation, the {@link UsernamePasswordCredential#getUsername()} * is mapped to the {@code uid} which will be used by the plugged-in instance of the * {@link YubiKeyAccountRegistry} * and the {@link UsernamePasswordCredential#getPassword()} is the received * one-time password token issued by the YubiKey device. */ @Override protected HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential transformedCredential) throws GeneralSecurityException, PreventedException { final String uid = transformedCredential.getUsername(); final String otp = transformedCredential.getPassword(); if (!YubicoClient.isValidOTPFormat(otp)) { logger.debug("Invalid OTP format [{}]", otp); throw new FailedLoginException("OTP format is invalid"); } final String publicId = YubicoClient.getPublicId(otp); if (this.registry != null &&!this.registry.isYubiKeyRegisteredFor(uid, publicId)) { logger.debug("YubiKey public id [{}] is not registered for user [{}]", publicId, uid); throw new AccountNotFoundException("YubiKey id is not recognized in registry"); } try { final VerificationResponse response = this.client.verify(otp); final ResponseStatus status = response.getStatus(); if (status.compareTo(ResponseStatus.OK) == 0) { logger.debug("YubiKey response status {} at {}", status, response.getTimestamp()); return createHandlerResult(transformedCredential, this.principalFactory.createPrincipal(uid), null); } throw new FailedLoginException("Authentication failed with status: " + status); } catch (final YubicoVerificationException | YubicoValidationFailure e) { logger.error(e.getMessage(), e); throw new FailedLoginException("YubiKey validation failed: " + e.getMessage()); } }
@Test(expected = AccountNotFoundException.class) public void checkAccountNotFound() throws Exception { final YubiKeyAuthenticationHandler handler = new YubiKeyAuthenticationHandler(CLIENT_ID, SECRET_KEY); handler.setRegistry(new YubiKeyAccountRegistry() { @Override public boolean isYubiKeyRegisteredFor(final String uid, final String yubikeyPublicId) { return false; } }); handler.authenticate(new UsernamePasswordCredential("casuser", OTP)); }
@Test public void verifyEncodeDecodeTGTImpl() throws Exception { final Credential userPassCredential = new UsernamePasswordCredential(USERNAME, PASSWORD); final AuthenticationBuilder bldr = new DefaultAuthenticationBuilder( new DefaultPrincipalFactory() .createPrincipal("user", Collections.unmodifiableMap(this.principalAttributes))); bldr.setAttributes(Collections.unmodifiableMap(this.principalAttributes)); bldr.setAuthenticationDate(new DateTime()); bldr.addCredential(new BasicCredentialMetaData(userPassCredential)); bldr.addFailure("error", AccountNotFoundException.class); bldr.addSuccess("authn", new DefaultHandlerResult( new AcceptUsersAuthenticationHandler(), new BasicCredentialMetaData(userPassCredential))); final TicketGrantingTicket expectedTGT = new TicketGrantingTicketImpl(TGT_ID, org.jasig.cas.services.TestUtils.getService(), null, bldr.build(), new NeverExpiresExpirationPolicy()); final ServiceTicket ticket = expectedTGT.grantServiceTicket(ST_ID, org.jasig.cas.services.TestUtils.getService(), new NeverExpiresExpirationPolicy(), false, true); CachedData result = transcoder.encode(expectedTGT); final TicketGrantingTicket resultTicket = (TicketGrantingTicket) transcoder.decode(result); assertEquals(expectedTGT, resultTicket); result = transcoder.encode(ticket); final ServiceTicket resultStTicket = (ServiceTicket) transcoder.decode(result); assertEquals(ticket, resultStTicket); }
@Test(expected = AccountNotFoundException.class) public void verifyAuthenticationFailsToFindUser() throws Exception { final QueryAndEncodeDatabaseAuthenticationHandler q = new QueryAndEncodeDatabaseAuthenticationHandler(this.dataSource, buildSql(), ALG_NAME); q.authenticateUsernamePasswordInternal(TestUtils.getCredentialsWithSameUsernameAndPassword()); }
@Test(expected = AccountNotFoundException.class) public void verifyFailsUserNotInMap() throws Exception { final UsernamePasswordCredential c = new UsernamePasswordCredential(); c.setUsername("fds"); c.setPassword("rutgers"); this.authenticationHandler.authenticate(c); }