use of org.apereo.cas.authentication.UsernamePasswordCredential in project cas by apereo.
the class AcceptUserGraphicsForAuthenticationAction method doExecute.
@Override
protected Event doExecute(final RequestContext requestContext) {
final String username = requestContext.getRequestParameters().get("username");
WebUtils.putCredential(requestContext, new UsernamePasswordCredential(username, null));
requestContext.getFlowScope().put("guaUsername", username);
return success();
}
use of org.apereo.cas.authentication.UsernamePasswordCredential in project cas by apereo.
the class PersonDirectoryAttributeResolutionController method releasePrincipalAttributes.
/**
* Release principal attributes map.
*
* @param username the username
* @param password the password
* @param service the service
* @param request the request
* @param response the response
* @return the map
* @throws Exception the exception
*/
@PostMapping(value = "/releaseattrs")
@ResponseBody
public Map<String, Object> releasePrincipalAttributes(@RequestParam final String username, @RequestParam final String password, @RequestParam final String service, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
ensureEndpointAccessIsAuthorized(request, response);
final Map<String, Object> resValidation = new HashMap<>();
final Service selectedService = this.serviceFactory.createService(service);
final RegisteredService registeredService = this.servicesManager.findServiceBy(selectedService);
final UsernamePasswordCredential credential = new UsernamePasswordCredential(username, password);
final AuthenticationResult result = this.authenticationSystemSupport.handleAndFinalizeSingleAuthenticationTransaction(selectedService, credential);
final Authentication authentication = result.getAuthentication();
final Principal principal = authentication.getPrincipal();
final Map<String, Object> attributesToRelease = registeredService.getAttributeReleasePolicy().getAttributes(principal, selectedService, registeredService);
final String principalId = registeredService.getUsernameAttributeProvider().resolveUsername(principal, selectedService, registeredService);
final Principal modifiedPrincipal = this.principalFactory.createPrincipal(principalId, attributesToRelease);
final AuthenticationBuilder builder = DefaultAuthenticationBuilder.newInstance(authentication);
builder.setPrincipal(modifiedPrincipal);
final Authentication finalAuthentication = builder.build();
final Assertion assertion = new DefaultAssertionBuilder(finalAuthentication).with(selectedService).with(CollectionUtils.wrap(finalAuthentication)).build();
final Map<String, Object> model = new LinkedHashMap<>();
model.put(CasViewConstants.MODEL_ATTRIBUTE_NAME_ASSERTION, assertion);
model.put(CasViewConstants.MODEL_ATTRIBUTE_NAME_SERVICE, selectedService);
resValidation.put("registeredService", registeredService);
String copy = renderViewAndGetResult(this.cas1ServiceSuccessView, model, request, response).getKey().getCopy();
resValidation.put("cas1Response", StringEscapeUtils.escapeXml11(copy));
if (casProperties.getView().getCas2().isV3ForwardCompatible()) {
copy = renderViewAndGetResult(this.cas3ServiceSuccessView, model, request, response).getKey().getCopy();
} else {
copy = renderViewAndGetResult(this.cas2ServiceSuccessView, model, request, response).getKey().getCopy();
}
resValidation.put("cas2Response", StringEscapeUtils.escapeXml11(copy));
copy = renderViewAndGetResult(this.cas3ServiceSuccessView, model, request, response).getKey().getCopy();
resValidation.put("cas3XmlResponse", StringEscapeUtils.escapeXml11(copy));
copy = renderViewAndGetResult(this.cas3ServiceJsonView, model, request, response).getValue().getStringCopy();
resValidation.put("cas3JsonResponse", copy);
response.reset();
return resValidation;
}
use of org.apereo.cas.authentication.UsernamePasswordCredential in project cas by apereo.
the class RestAuthenticationHandler method authenticateUsernamePasswordInternal.
@Override
protected AuthenticationHandlerExecutionResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential c, final String originalPassword) throws GeneralSecurityException {
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());
}
final Principal principal = this.principalFactory.createPrincipal(principalFromRest.getId(), principalFromRest.getAttributes());
return createHandlerResult(c, principal, 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_FAILED) {
throw new AccountExpiredException("Could not authenticate expired account for " + c.getUsername());
}
if (e.getStatusCode() == HttpStatus.PRECONDITION_REQUIRED) {
throw new AccountPasswordMustChangeException("Account password must change 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());
}
use of org.apereo.cas.authentication.UsernamePasswordCredential in project cas by apereo.
the class X509CredentialsAuthenticationHandlerTests method getTestParameters.
/**
* Gets the unit test parameters.
*
* @return Test parameter data.
*/
@Parameters
public static Collection<Object[]> getTestParameters() {
final Collection<Object[]> params = new ArrayList<>();
X509CredentialsAuthenticationHandler handler;
X509CertificateCredential credential;
// Test case #1: Unsupported credential type
handler = new X509CredentialsAuthenticationHandler(RegexUtils.createPattern(".*"));
params.add(new Object[] { handler, new UsernamePasswordCredential(), false, null });
// Test case #2:Valid certificate
handler = new X509CredentialsAuthenticationHandler(RegexUtils.createPattern(".*"));
credential = new X509CertificateCredential(createCertificates(USER_VALID_CRT));
params.add(new Object[] { handler, credential, true, new DefaultAuthenticationHandlerExecutionResult(handler, credential, new DefaultPrincipalFactory().createPrincipal(credential.getId())) });
// Test case #3: Expired certificate
handler = new X509CredentialsAuthenticationHandler(RegexUtils.createPattern(".*"));
params.add(new Object[] { handler, new X509CertificateCredential(createCertificates("user-expired.crt")), true, new CertificateExpiredException() });
// Test case #4: Untrusted issuer
handler = new X509CredentialsAuthenticationHandler(RegexUtils.createPattern("CN=\\w+,OU=CAS,O=Jasig,L=Westminster,ST=Colorado,C=US"), true, false, false);
params.add(new Object[] { handler, new X509CertificateCredential(createCertificates("snake-oil.crt")), true, new FailedLoginException() });
// Test case #5: Disallowed subject
handler = new X509CredentialsAuthenticationHandler(RegexUtils.createPattern(".*"), true, RegexUtils.createPattern("CN=\\w+,OU=CAS,O=Jasig,L=Westminster,ST=Colorado,C=US"));
params.add(new Object[] { handler, new X509CertificateCredential(createCertificates("snake-oil.crt")), true, new FailedLoginException() });
// Test case #6: Check key usage on a cert without keyUsage extension
handler = new X509CredentialsAuthenticationHandler(RegexUtils.createPattern(".*"), false, true, false);
credential = new X509CertificateCredential(createCertificates(USER_VALID_CRT));
params.add(new Object[] { handler, credential, true, new DefaultAuthenticationHandlerExecutionResult(handler, credential, new DefaultPrincipalFactory().createPrincipal(credential.getId())) });
// Test case #7: Require key usage on a cert without keyUsage extension
handler = new X509CredentialsAuthenticationHandler(RegexUtils.createPattern(".*"), false, true, true);
params.add(new Object[] { handler, new X509CertificateCredential(createCertificates(USER_VALID_CRT)), true, new FailedLoginException() });
// Test case #8: Require key usage on a cert with acceptable keyUsage extension values
handler = new X509CredentialsAuthenticationHandler(RegexUtils.createPattern(".*"), false, true, true);
credential = new X509CertificateCredential(createCertificates("user-valid-keyUsage.crt"));
params.add(new Object[] { handler, credential, true, new DefaultAuthenticationHandlerExecutionResult(handler, credential, new DefaultPrincipalFactory().createPrincipal(credential.getId())) });
// Test case #9: Require key usage on a cert with unacceptable keyUsage extension values
handler = new X509CredentialsAuthenticationHandler(RegexUtils.createPattern(".*"), false, true, true);
params.add(new Object[] { handler, new X509CertificateCredential(createCertificates("user-invalid-keyUsage.crt")), true, new FailedLoginException() });
// ===================================
// Revocation tests
// ===================================
ResourceCRLRevocationChecker checker;
// Test case #10: Valid certificate with CRL checking
checker = new ResourceCRLRevocationChecker(new ClassPathResource("userCA-valid.crl"));
checker.init();
handler = new X509CredentialsAuthenticationHandler(RegexUtils.createPattern(".*"), checker);
credential = new X509CertificateCredential(createCertificates(USER_VALID_CRT));
params.add(new Object[] { handler, new X509CertificateCredential(createCertificates(USER_VALID_CRT)), true, new DefaultAuthenticationHandlerExecutionResult(handler, credential, new DefaultPrincipalFactory().createPrincipal(credential.getId())) });
// Test case #11: Revoked end user certificate
checker = new ResourceCRLRevocationChecker(new ClassPathResource("userCA-valid.crl"));
checker.init();
handler = new X509CredentialsAuthenticationHandler(RegexUtils.createPattern(".*"), checker);
params.add(new Object[] { handler, new X509CertificateCredential(createCertificates("user-revoked.crt")), true, new RevokedCertificateException(ZonedDateTime.now(ZoneOffset.UTC), null) });
// Test case #12: Valid certificate on expired CRL data
final ThresholdExpiredCRLRevocationPolicy zeroThresholdPolicy = new ThresholdExpiredCRLRevocationPolicy(0);
checker = new ResourceCRLRevocationChecker(new ClassPathResource("userCA-expired.crl"), null, zeroThresholdPolicy);
checker.init();
handler = new X509CredentialsAuthenticationHandler(RegexUtils.createPattern(".*"), checker);
params.add(new Object[] { handler, new X509CertificateCredential(createCertificates(USER_VALID_CRT)), true, new ExpiredCRLException(null, ZonedDateTime.now(ZoneOffset.UTC)) });
return params;
}
use of org.apereo.cas.authentication.UsernamePasswordCredential in project cas by apereo.
the class SimpleTestUsernamePasswordAuthenticationHandler method authenticate.
@Override
public HandlerResult authenticate(final Credential credential) throws GeneralSecurityException, PreventedException {
final UsernamePasswordCredential usernamePasswordCredential = (UsernamePasswordCredential) credential;
final String username = usernamePasswordCredential.getUsername();
final String password = usernamePasswordCredential.getPassword();
final Exception exception = this.usernameErrorMap.get(username);
if (exception instanceof GeneralSecurityException) {
throw (GeneralSecurityException) exception;
} else if (exception instanceof PreventedException) {
throw (PreventedException) exception;
} else if (exception instanceof RuntimeException) {
throw (RuntimeException) exception;
} else if (exception != null) {
LOGGER.debug("Cannot throw checked exception [{}] since it is not declared by method signature.", exception.getClass().getName(), exception);
}
if (StringUtils.hasText(username) && StringUtils.hasText(password) && username.equals(password)) {
LOGGER.debug("User [{}] was successfully authenticated.", username);
return new DefaultHandlerResult(this, new BasicCredentialMetaData(credential), this.principalFactory.createPrincipal(username));
}
LOGGER.debug("User [{}] failed authentication", username);
throw new FailedLoginException();
}
Aggregations