Search in sources :

Example 41 with JEEContext

use of org.pac4j.core.context.JEEContext in project cas by apereo.

the class ECPSamlIdPProfileHandlerController method extractBasicAuthenticationCredential.

private Credential extractBasicAuthenticationCredential(final HttpServletRequest request, final HttpServletResponse response) {
    val extractor = new BasicAuthExtractor();
    val webContext = new JEEContext(request, response);
    val credentialsResult = extractor.extract(webContext, configurationContext.getSessionStore());
    if (credentialsResult.isPresent()) {
        val credentials = (UsernamePasswordCredentials) credentialsResult.get();
        LOGGER.debug("Received basic authentication ECP request from credentials [{}]", credentials);
        return new UsernamePasswordCredential(credentials.getUsername(), credentials.getPassword());
    }
    return null;
}
Also used : lombok.val(lombok.val) BasicAuthExtractor(org.pac4j.core.credentials.extractor.BasicAuthExtractor) JEEContext(org.pac4j.core.context.JEEContext) UsernamePasswordCredential(org.apereo.cas.authentication.credential.UsernamePasswordCredential) UsernamePasswordCredentials(org.pac4j.core.credentials.UsernamePasswordCredentials)

Example 42 with JEEContext

use of org.pac4j.core.context.JEEContext in project cas by apereo.

the class SamlIdPMultifactorAuthenticationTrigger method isActivated.

@Override
public Optional<MultifactorAuthenticationProvider> isActivated(final Authentication authentication, final RegisteredService registeredService, final HttpServletRequest request, final HttpServletResponse response, final Service service) {
    val context = new JEEContext(request, response);
    val result = SamlIdPUtils.retrieveSamlRequest(context, distributedSessionStore, openSamlConfigBean, AuthnRequest.class);
    val mappings = getAuthenticationContextMappings();
    return result.map(pair -> (AuthnRequest) pair.getLeft()).flatMap(authnRequest -> authnRequest.getRequestedAuthnContext().getAuthnContextClassRefs().stream().filter(Objects::nonNull).filter(ref -> StringUtils.isNotBlank(ref.getURI())).filter(ref -> {
        val clazz = ref.getURI();
        return mappings.containsKey(clazz);
    }).findFirst().map(mapped -> mappings.get(mapped.getURI()))).flatMap(id -> {
        val providerMap = MultifactorAuthenticationUtils.getAvailableMultifactorAuthenticationProviders(applicationContext);
        return MultifactorAuthenticationUtils.resolveProvider(providerMap, id);
    });
}
Also used : lombok.val(lombok.val) CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) RequiredArgsConstructor(lombok.RequiredArgsConstructor) lombok.val(lombok.val) HttpServletResponse(javax.servlet.http.HttpServletResponse) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) MultifactorAuthenticationProvider(org.apereo.cas.authentication.MultifactorAuthenticationProvider) MultifactorAuthenticationTrigger(org.apereo.cas.authentication.MultifactorAuthenticationTrigger) StringUtils(org.apache.commons.lang3.StringUtils) SessionStore(org.pac4j.core.context.session.SessionStore) ApplicationContext(org.springframework.context.ApplicationContext) RegisteredService(org.apereo.cas.services.RegisteredService) SamlIdPUtils(org.apereo.cas.support.saml.SamlIdPUtils) OpenSamlConfigBean(org.apereo.cas.support.saml.OpenSamlConfigBean) HttpRequestUtils(org.apereo.cas.util.HttpRequestUtils) Objects(java.util.Objects) HttpServletRequest(javax.servlet.http.HttpServletRequest) Authentication(org.apereo.cas.authentication.Authentication) Service(org.apereo.cas.authentication.principal.Service) Map(java.util.Map) CollectionUtils(org.apereo.cas.util.CollectionUtils) Optional(java.util.Optional) MultifactorAuthenticationUtils(org.apereo.cas.authentication.MultifactorAuthenticationUtils) JEEContext(org.pac4j.core.context.JEEContext) JEEContext(org.pac4j.core.context.JEEContext) Objects(java.util.Objects)

Example 43 with JEEContext

use of org.pac4j.core.context.JEEContext in project cas by apereo.

the class SamlIdPMultifactorAuthenticationTrigger method supports.

@Override
public boolean supports(final HttpServletRequest request, final RegisteredService registeredService, final Authentication authentication, final Service service) {
    if (!getAuthenticationContextMappings().isEmpty()) {
        val response = HttpRequestUtils.getHttpServletResponseFromRequestAttributes();
        val context = new JEEContext(request, response);
        val result = SamlIdPUtils.retrieveSamlRequest(context, distributedSessionStore, openSamlConfigBean, AuthnRequest.class);
        if (result.isPresent()) {
            val authnRequest = (AuthnRequest) result.get().getLeft();
            return authnRequest.getRequestedAuthnContext() != null && authnRequest.getRequestedAuthnContext().getAuthnContextClassRefs() != null && !authnRequest.getRequestedAuthnContext().getAuthnContextClassRefs().isEmpty();
        }
    }
    return false;
}
Also used : lombok.val(lombok.val) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) JEEContext(org.pac4j.core.context.JEEContext)

Example 44 with JEEContext

use of org.pac4j.core.context.JEEContext in project cas by apereo.

the class OAuth20AuthorizeEndpointController method prepareAccessTokenRequestContext.

/**
 * Build access token request context.
 *
 * @param authzRequest      the authz request
 * @param registeredService the registered service
 * @param context           the context
 * @param service           the service
 * @param authentication    the authentication
 * @return the access token request context
 * @throws Exception the exception
 */
protected AccessTokenRequestContext prepareAccessTokenRequestContext(final OAuth20AuthorizationRequest authzRequest, final OAuthRegisteredService registeredService, final JEEContext context, final Service service, final Authentication authentication) throws Exception {
    var payloadBuilder = AccessTokenRequestContext.builder();
    if (authzRequest.isSingleSignOnSessionRequired()) {
        val tgt = getConfigurationContext().fetchTicketGrantingTicketFrom(context);
        payloadBuilder = payloadBuilder.ticketGrantingTicket(tgt);
    }
    val redirectUri = OAuth20Utils.getRequestParameter(context, OAuth20Constants.REDIRECT_URI).map(String::valueOf).orElse(StringUtils.EMPTY);
    val grantType = context.getRequestParameter(OAuth20Constants.GRANT_TYPE).map(String::valueOf).orElseGet(OAuth20GrantTypes.AUTHORIZATION_CODE::getType).toUpperCase();
    val scopes = OAuth20Utils.parseRequestScopes(context);
    val codeChallenge = context.getRequestParameter(OAuth20Constants.CODE_CHALLENGE).map(String::valueOf).orElse(StringUtils.EMPTY);
    val codeChallengeMethod = context.getRequestParameter(OAuth20Constants.CODE_CHALLENGE_METHOD).map(String::valueOf).orElse(StringUtils.EMPTY).toUpperCase();
    val userProfile = OAuth20Utils.getAuthenticatedUserProfile(context, getConfigurationContext().getSessionStore());
    val claims = OAuth20Utils.parseRequestClaims(context);
    val holder = payloadBuilder.service(service).authentication(authentication).registeredService(registeredService).grantType(OAuth20Utils.getGrantType(context)).responseType(OAuth20Utils.getResponseType(context)).codeChallenge(codeChallenge).codeChallengeMethod(codeChallengeMethod).scopes(scopes).clientId(authzRequest.getClientId()).redirectUri(redirectUri).userProfile(userProfile).claims(claims).responseMode(OAuth20Utils.getResponseModeType(context)).build();
    context.getRequestParameters().keySet().forEach(key -> context.getRequestParameter(key).ifPresent(value -> holder.getParameters().put(key, value)));
    LOGGER.debug("Building authorization response for grant type [{}] with scopes [{}] for client id [{}]", grantType, scopes, authzRequest.getClientId());
    return holder;
}
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) OAuth20GrantTypes(org.apereo.cas.support.oauth.OAuth20GrantTypes)

Example 45 with JEEContext

use of org.pac4j.core.context.JEEContext 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)

Aggregations

JEEContext (org.pac4j.core.context.JEEContext)224 lombok.val (lombok.val)215 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)158 Test (org.junit.jupiter.api.Test)157 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)155 MockTicketGrantingTicket (org.apereo.cas.mock.MockTicketGrantingTicket)34 ProfileManager (org.pac4j.core.profile.ProfileManager)28 UsernamePasswordCredentials (org.pac4j.core.credentials.UsernamePasswordCredentials)24 CommonProfile (org.pac4j.core.profile.CommonProfile)22 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)16 HashMap (java.util.HashMap)15 HttpServletRequest (javax.servlet.http.HttpServletRequest)14 HttpServletResponse (javax.servlet.http.HttpServletResponse)14 RedirectView (org.springframework.web.servlet.view.RedirectView)14 CasProfile (org.pac4j.cas.profile.CasProfile)13 ServletExternalContext (org.springframework.webflow.context.servlet.ServletExternalContext)13 MockRequestContext (org.springframework.webflow.test.MockRequestContext)13 GetMapping (org.springframework.web.bind.annotation.GetMapping)11 Map (java.util.Map)10 Slf4j (lombok.extern.slf4j.Slf4j)10