Search in sources :

Example 1 with PreventedException

use of org.apereo.cas.authentication.PreventedException in project cas by apereo.

the class ClientAuthenticationHandler method doAuthentication.

@Override
protected AuthenticationHandlerExecutionResult doAuthentication(final Credential credential) throws GeneralSecurityException, PreventedException {
    try {
        final ClientCredential clientCredentials = (ClientCredential) credential;
        LOGGER.debug("Located client credentials as [{}]", clientCredentials);
        final Credentials credentials = clientCredentials.getCredentials();
        LOGGER.debug("Client name: [{}]", clientCredentials.getClientName());
        // get client
        final Client client = this.clients.findClient(clientCredentials.getClientName());
        LOGGER.debug("Delegated client is: [{}]", client);
        final HttpServletRequest request = WebUtils.getHttpServletRequestFromExternalWebflowContext();
        final HttpServletResponse response = WebUtils.getHttpServletResponseFromExternalWebflowContext();
        final WebContext webContext = Pac4jUtils.getPac4jJ2EContext(request, response);
        final UserProfile userProfile = client.getUserProfile(credentials, webContext);
        LOGGER.debug("Final user profile is: [{}]", userProfile);
        return createResult(clientCredentials, userProfile);
    } catch (final HttpAction e) {
        throw new PreventedException(e);
    }
}
Also used : ClientCredential(org.apereo.cas.authentication.principal.ClientCredential) HttpServletRequest(javax.servlet.http.HttpServletRequest) WebContext(org.pac4j.core.context.WebContext) UserProfile(org.pac4j.core.profile.UserProfile) HttpServletResponse(javax.servlet.http.HttpServletResponse) PreventedException(org.apereo.cas.authentication.PreventedException) Client(org.pac4j.core.client.Client) Credentials(org.pac4j.core.credentials.Credentials) HttpAction(org.pac4j.core.exception.HttpAction)

Example 2 with PreventedException

use of org.apereo.cas.authentication.PreventedException in project cas by apereo.

the class OAuth20AuthorizeEndpointController method buildAuthorizationForRequest.

/**
 * Build callback url for request string.
 *
 * @param registeredService the registered service
 * @param context           the context
 * @param service           the service
 * @param authentication    the authentication
 * @return the model and view
 */
protected ModelAndView buildAuthorizationForRequest(final OAuthRegisteredService registeredService, final JEEContext context, final Service service, final Authentication authentication) {
    val registeredBuilders = getConfigurationContext().getOauthAuthorizationResponseBuilders().getObject();
    val authzRequest = registeredBuilders.stream().sorted(OrderComparator.INSTANCE).map(builder -> toAuthorizationRequest(registeredService, context, service, authentication, builder)).filter(Objects::nonNull).filter(Optional::isPresent).findFirst().orElseThrow(() -> new IllegalArgumentException("Unable to build authorization request")).get().build();
    val payload = Optional.ofNullable(authzRequest.getAccessTokenRequest()).orElseGet(Unchecked.supplier(() -> prepareAccessTokenRequestContext(authzRequest, registeredService, context, service, authentication)));
    return registeredBuilders.stream().sorted(OrderComparator.INSTANCE).filter(b -> b.supports(authzRequest)).findFirst().map(Unchecked.function(builder -> {
        if (authzRequest.isSingleSignOnSessionRequired() && payload.getTicketGrantingTicket() == null) {
            val message = String.format("Missing ticket-granting-ticket for client id [%s] and service [%s]", authzRequest.getClientId(), registeredService.getName());
            LOGGER.error(message);
            return OAuth20Utils.produceErrorView(new PreventedException(message));
        }
        return builder.build(payload);
    })).orElseGet(() -> OAuth20Utils.produceErrorView(new PreventedException("Could not build the callback response")));
}
Also used : lombok.val(lombok.val) RegisteredServiceAccessStrategyUtils(org.apereo.cas.services.RegisteredServiceAccessStrategyUtils) StringUtils(org.apache.commons.lang3.StringUtils) WebContext(org.pac4j.core.context.WebContext) AuthenticationCredentialsThreadLocalBinder(org.apereo.cas.authentication.AuthenticationCredentialsThreadLocalBinder) AccessTokenRequestContext(org.apereo.cas.support.oauth.web.response.accesstoken.ext.AccessTokenRequestContext) LoggingUtils(org.apereo.cas.util.LoggingUtils) HttpServletRequest(javax.servlet.http.HttpServletRequest) Authentication(org.apereo.cas.authentication.Authentication) OAuth20AuthorizationRequest(org.apereo.cas.support.oauth.web.response.OAuth20AuthorizationRequest) GetMapping(org.springframework.web.bind.annotation.GetMapping) OAuth20AuthorizationResponseBuilder(org.apereo.cas.support.oauth.web.response.callback.OAuth20AuthorizationResponseBuilder) JEEContext(org.pac4j.core.context.JEEContext) PostMapping(org.springframework.web.bind.annotation.PostMapping) OAuth20Constants(org.apereo.cas.support.oauth.OAuth20Constants) Unchecked(org.jooq.lambda.Unchecked) OAuth20Utils(org.apereo.cas.support.oauth.util.OAuth20Utils) AuditableContext(org.apereo.cas.audit.AuditableContext) OAuth20GrantTypes(org.apereo.cas.support.oauth.OAuth20GrantTypes) lombok.val(lombok.val) HttpServletResponse(javax.servlet.http.HttpServletResponse) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) ProfileManager(org.pac4j.core.profile.ProfileManager) OrderComparator(org.springframework.core.OrderComparator) Objects(java.util.Objects) HttpStatus(org.springframework.http.HttpStatus) ModelAndView(org.springframework.web.servlet.ModelAndView) Slf4j(lombok.extern.slf4j.Slf4j) Service(org.apereo.cas.authentication.principal.Service) Optional(java.util.Optional) PreventedException(org.apereo.cas.authentication.PreventedException) Optional(java.util.Optional) PreventedException(org.apereo.cas.authentication.PreventedException)

Example 3 with PreventedException

use of org.apereo.cas.authentication.PreventedException in project cas by apereo.

the class AllAuthenticationHandlersSucceededAuthenticationPolicyTests method verifyOperationPrevented.

@Test
public void verifyOperationPrevented() {
    val input = new AllAuthenticationHandlersSucceededAuthenticationPolicy();
    val builder = new DefaultAuthenticationBuilder(CoreAuthenticationTestUtils.getPrincipal());
    val authn = builder.addFailure("Prevented", new PreventedException("error")).build();
    assertFalse(input.isSatisfiedBy(authn, Set.of(), mock(ConfigurableApplicationContext.class), Optional.empty()).isSuccess());
}
Also used : lombok.val(lombok.val) DefaultAuthenticationBuilder(org.apereo.cas.authentication.DefaultAuthenticationBuilder) ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) PreventedException(org.apereo.cas.authentication.PreventedException) Test(org.junit.jupiter.api.Test)

Example 4 with PreventedException

use of org.apereo.cas.authentication.PreventedException in project cas by apereo.

the class AtLeastOneCredentialValidatedAuthenticationPolicyTests method verifyHandlerCountMismatch.

@Test
public void verifyHandlerCountMismatch() throws Exception {
    val input = new AtLeastOneCredentialValidatedAuthenticationPolicy(true);
    val builder = new DefaultAuthenticationBuilder(CoreAuthenticationTestUtils.getPrincipal());
    val authn = builder.addFailure("Prevented", new PreventedException("error")).build();
    assertFalse(input.isSatisfiedBy(authn, Set.of(), mock(ConfigurableApplicationContext.class), Optional.empty()).isSuccess());
}
Also used : lombok.val(lombok.val) DefaultAuthenticationBuilder(org.apereo.cas.authentication.DefaultAuthenticationBuilder) ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) PreventedException(org.apereo.cas.authentication.PreventedException) Test(org.junit.jupiter.api.Test)

Example 5 with PreventedException

use of org.apereo.cas.authentication.PreventedException in project cas by apereo.

the class QueryDatabaseAuthenticationHandler method authenticateUsernamePasswordInternal.

@Override
protected AuthenticationHandlerExecutionResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential, final String originalPassword) throws GeneralSecurityException, PreventedException {
    val attributes = Maps.<String, List<Object>>newHashMapWithExpectedSize(this.principalAttributeMap.size());
    val username = credential.getUsername();
    val password = credential.getPassword();
    try {
        val dbFields = query(credential);
        if (dbFields.containsKey(properties.getFieldPassword())) {
            val dbPassword = (String) dbFields.get(properties.getFieldPassword());
            val originalPasswordMatchFails = StringUtils.isNotBlank(originalPassword) && !matches(originalPassword, dbPassword);
            val originalPasswordEquals = StringUtils.isBlank(originalPassword) && !StringUtils.equals(password, dbPassword);
            if (originalPasswordMatchFails || originalPasswordEquals) {
                throw new FailedLoginException("Password does not match value on record.");
            }
        } else {
            LOGGER.debug("Password field is not found in the query results. Checking for result count...");
            if (!dbFields.containsKey("total")) {
                throw new FailedLoginException("Missing field 'total' from the query results for " + username);
            }
            val count = dbFields.get("total");
            if (count == null || !NumberUtils.isCreatable(count.toString())) {
                throw new FailedLoginException("Missing field value 'total' from the query results for " + username + " or value not parseable as a number");
            }
            val number = NumberUtils.createNumber(count.toString());
            if (number.longValue() != 1) {
                throw new FailedLoginException("No records found for user " + username);
            }
        }
        if (StringUtils.isNotBlank(properties.getFieldDisabled()) && dbFields.containsKey(properties.getFieldDisabled())) {
            val dbDisabled = dbFields.get(properties.getFieldDisabled()).toString();
            if (BooleanUtils.toBoolean(dbDisabled) || "1".equals(dbDisabled)) {
                throw new AccountDisabledException("Account has been disabled");
            }
        }
        if (StringUtils.isNotBlank(properties.getFieldExpired()) && dbFields.containsKey(properties.getFieldExpired())) {
            val dbExpired = dbFields.get(properties.getFieldExpired()).toString();
            if (BooleanUtils.toBoolean(dbExpired) || "1".equals(dbExpired)) {
                throw new AccountPasswordMustChangeException("Password has expired");
            }
        }
        collectPrincipalAttributes(attributes, dbFields);
    } catch (final IncorrectResultSizeDataAccessException e) {
        if (e.getActualSize() == 0) {
            throw new AccountNotFoundException(username + " not found with SQL query");
        }
        throw new FailedLoginException("Multiple records found for " + username);
    } catch (final DataAccessException e) {
        throw new PreventedException(e);
    }
    val principal = this.principalFactory.createPrincipal(username, attributes);
    return createHandlerResult(credential, principal, new ArrayList<>(0));
}
Also used : lombok.val(lombok.val) FailedLoginException(javax.security.auth.login.FailedLoginException) IncorrectResultSizeDataAccessException(org.springframework.dao.IncorrectResultSizeDataAccessException) ArrayList(java.util.ArrayList) List(java.util.List) PreventedException(org.apereo.cas.authentication.PreventedException) AccountPasswordMustChangeException(org.apereo.cas.authentication.exceptions.AccountPasswordMustChangeException) AccountNotFoundException(javax.security.auth.login.AccountNotFoundException) AccountDisabledException(org.apereo.cas.authentication.exceptions.AccountDisabledException) DataAccessException(org.springframework.dao.DataAccessException) IncorrectResultSizeDataAccessException(org.springframework.dao.IncorrectResultSizeDataAccessException)

Aggregations

PreventedException (org.apereo.cas.authentication.PreventedException)18 lombok.val (lombok.val)15 FailedLoginException (javax.security.auth.login.FailedLoginException)9 GeneralSecurityException (java.security.GeneralSecurityException)5 AccountNotFoundException (javax.security.auth.login.AccountNotFoundException)5 DefaultAuthenticationBuilder (org.apereo.cas.authentication.DefaultAuthenticationBuilder)4 Test (org.junit.jupiter.api.Test)4 ConfigurableApplicationContext (org.springframework.context.ConfigurableApplicationContext)4 StringUtils (org.apache.commons.lang3.StringUtils)3 Authentication (org.apereo.cas.authentication.Authentication)3 AccountDisabledException (org.apereo.cas.authentication.exceptions.AccountDisabledException)3 Objects (java.util.Objects)2 Optional (java.util.Optional)2 AccountExpiredException (javax.security.auth.login.AccountExpiredException)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 Slf4j (lombok.extern.slf4j.Slf4j)2 WebContext (org.pac4j.core.context.WebContext)2 DataAccessException (org.springframework.dao.DataAccessException)2 IGoogleAuthenticator (com.warrenstrange.googleauth.IGoogleAuthenticator)1