Search in sources :

Example 1 with JEEContext

use of org.pac4j.jee.context.JEEContext in project spring-security-pac4j-demo by pac4j.

the class ForceLoginFilter method doFilter.

@Override
public void doFilter(final ServletRequest req, final ServletResponse resp, final FilterChain chain) throws IOException, ServletException {
    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) resp;
    final JEEContext context = new JEEContext(request, response);
    final Client client = config.getClients().findClient(request.getParameter(Pac4jConstants.DEFAULT_CLIENT_NAME_PARAMETER)).get();
    HttpAction action;
    try {
        action = (HttpAction) client.getRedirectionAction(context, JEESessionStore.INSTANCE).get();
    } catch (final HttpAction e) {
        action = e;
    }
    JEEHttpActionAdapter.INSTANCE.adapt(action, context);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) JEEContext(org.pac4j.jee.context.JEEContext) HttpServletResponse(javax.servlet.http.HttpServletResponse) Client(org.pac4j.core.client.Client) HttpAction(org.pac4j.core.exception.http.HttpAction)

Example 2 with JEEContext

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

the class EndpointLdapAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    try {
        val username = authentication.getPrincipal().toString();
        val credentials = authentication.getCredentials();
        val password = Optional.ofNullable(credentials).map(Object::toString).orElse(null);
        if (StringUtils.isBlank(password)) {
            throw new IllegalArgumentException("Password cannot be blank");
        }
        LOGGER.debug("Preparing LDAP authentication request for user [{}]", username);
        val request = new AuthenticationRequest(username, new Credential(password), ReturnAttributes.ALL.value());
        LOGGER.debug("Executing LDAP authentication request for user [{}]", username);
        val response = this.authenticator.authenticate(request);
        LOGGER.debug("LDAP response: [{}]", response);
        if (response.isSuccess()) {
            val roles = securityProperties.getUser().getRoles();
            if (roles.isEmpty()) {
                LOGGER.info("No user security roles are defined to enable authorization. User [{}] is considered authorized", username);
                return generateAuthenticationToken(authentication, new ArrayList<>(0));
            }
            val entry = response.getLdapEntry();
            val profile = new CommonProfile();
            profile.setId(username);
            entry.getAttributes().forEach(a -> profile.addAttribute(a.getName(), a.getStringValues()));
            LOGGER.debug("Collected user profile [{}]", profile);
            val context = new JEEContext(HttpRequestUtils.getHttpServletRequestFromRequestAttributes(), HttpRequestUtils.getHttpServletResponseFromRequestAttributes());
            val authZGen = buildAuthorizationGenerator();
            authZGen.generate(context, JEESessionStore.INSTANCE, profile);
            LOGGER.debug("Assembled user profile with roles after generating authorization claims [{}]", profile);
            val authorities = profile.getRoles().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toCollection(ArrayList::new));
            LOGGER.debug("List of authorities remapped from profile roles are [{}]", authorities);
            val authorizer = new RequireAnyRoleAuthorizer(roles);
            LOGGER.debug("Executing authorization for expected admin roles [{}]", authorizer.getElements());
            if (authorizer.isAllAuthorized(context, JEESessionStore.INSTANCE, CollectionUtils.wrap(profile))) {
                return generateAuthenticationToken(authentication, authorities);
            }
            LOGGER.warn("User [{}] is not authorized to access the requested resource allowed to roles [{}]", username, authorizer.getElements());
        } else {
            LOGGER.warn("LDAP authentication response produced no results for [{}]", username);
        }
    } catch (final Exception e) {
        LoggingUtils.error(LOGGER, e);
        throw new InsufficientAuthenticationException("Unexpected LDAP error", e);
    }
    throw new BadCredentialsException("Could not authenticate provided credentials");
}
Also used : lombok.val(lombok.val) Credential(org.ldaptive.Credential) CommonProfile(org.pac4j.core.profile.CommonProfile) JEEContext(org.pac4j.jee.context.JEEContext) AuthenticationRequest(org.ldaptive.auth.AuthenticationRequest) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) RequireAnyRoleAuthorizer(org.pac4j.core.authorization.authorizer.RequireAnyRoleAuthorizer) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationException(org.springframework.security.core.AuthenticationException) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException)

Example 3 with JEEContext

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

the class AbstractSamlIdPProfileHandlerController method storeAuthenticationRequest.

/**
 * Store authentication request.
 *
 * @param request  the request
 * @param response the response
 * @param context  the pair
 * @throws Exception the exception
 */
@Synchronized
protected void storeAuthenticationRequest(final HttpServletRequest request, final HttpServletResponse response, final Pair<? extends SignableSAMLObject, MessageContext> context) throws Exception {
    val webContext = new JEEContext(request, response);
    SamlIdPUtils.storeSamlRequest(webContext, configurationContext.getOpenSamlConfigBean(), configurationContext.getSessionStore(), context);
}
Also used : lombok.val(lombok.val) JEEContext(org.pac4j.jee.context.JEEContext) Synchronized(lombok.Synchronized)

Example 4 with JEEContext

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

the class AbstractSamlIdPProfileHandlerController method issueAuthenticationRequestRedirect.

/**
 * Redirect request for authentication.
 *
 * @param pair     the pair
 * @param request  the request
 * @param response the response
 * @return the model and view
 * @throws Exception the exception
 */
protected ModelAndView issueAuthenticationRequestRedirect(final Pair<? extends SignableSAMLObject, MessageContext> pair, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    val authnRequest = (AuthnRequest) pair.getLeft();
    val serviceUrl = constructServiceUrl(request, response, pair);
    LOGGER.debug("Created service url [{}]", DigestUtils.abbreviate(serviceUrl));
    val properties = configurationContext.getCasProperties();
    val urlToRedirectTo = CommonUtils.constructRedirectUrl(properties.getServer().getLoginUrl(), CasProtocolConstants.PARAMETER_SERVICE, serviceUrl, authnRequest.isForceAuthn(), authnRequest.isPassive());
    LOGGER.debug("Redirecting SAML authN request to [{}]", urlToRedirectTo);
    val type = properties.getAuthn().getSamlIdp().getCore().getSessionStorageType();
    if (type == SamlIdPCoreProperties.SessionStorageTypes.BROWSER_SESSION_STORAGE) {
        val context = new JEEContext(request, response);
        val sessionStorage = configurationContext.getSessionStore().getTrackableSession(context).map(BrowserSessionStorage.class::cast).orElseThrow(() -> new IllegalStateException("Unable to determine trackable session for storage"));
        sessionStorage.setDestinationUrl(urlToRedirectTo);
        return new ModelAndView(CasWebflowConstants.VIEW_ID_SESSION_STORAGE_WRITE, BrowserSessionStorage.KEY_SESSION_STORAGE, sessionStorage);
    }
    LOGGER.debug("Redirecting SAML authN request to [{}]", urlToRedirectTo);
    val mv = new ModelAndView(new RedirectView(urlToRedirectTo));
    mv.setStatus(HttpStatus.FOUND);
    return mv;
}
Also used : lombok.val(lombok.val) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) JEEContext(org.pac4j.jee.context.JEEContext) ModelAndView(org.springframework.web.servlet.ModelAndView) RedirectView(org.springframework.web.servlet.view.RedirectView)

Example 5 with JEEContext

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

the class AbstractSamlIdPProfileHandlerController method retrieveAuthenticationRequest.

/**
 * Retrieve authentication request.
 *
 * @param response the response
 * @param request  the request
 * @return the authn request
 */
@Synchronized
protected final Pair<? extends RequestAbstractType, MessageContext> retrieveAuthenticationRequest(final HttpServletResponse response, final HttpServletRequest request) {
    LOGGER.info("Received SAML callback profile request [{}]", request.getRequestURI());
    val webContext = new JEEContext(request, response);
    return SamlIdPUtils.retrieveSamlRequest(webContext, configurationContext.getSessionStore(), configurationContext.getOpenSamlConfigBean(), AuthnRequest.class).orElseThrow(() -> new IllegalArgumentException("SAML request or context could not be determined from session store"));
}
Also used : lombok.val(lombok.val) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) JEEContext(org.pac4j.jee.context.JEEContext) Synchronized(lombok.Synchronized)

Aggregations

JEEContext (org.pac4j.jee.context.JEEContext)227 lombok.val (lombok.val)224 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)166 Test (org.junit.jupiter.api.Test)163 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)161 MockTicketGrantingTicket (org.apereo.cas.mock.MockTicketGrantingTicket)34 ProfileManager (org.pac4j.core.profile.ProfileManager)27 UsernamePasswordCredentials (org.pac4j.core.credentials.UsernamePasswordCredentials)24 CommonProfile (org.pac4j.core.profile.CommonProfile)21 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)16 ServletExternalContext (org.springframework.webflow.context.servlet.ServletExternalContext)14 MockRequestContext (org.springframework.webflow.test.MockRequestContext)14 HashMap (java.util.HashMap)13 CasProfile (org.pac4j.cas.profile.CasProfile)13 RedirectView (org.springframework.web.servlet.view.RedirectView)13 HttpServletRequest (javax.servlet.http.HttpServletRequest)12 Map (java.util.Map)10 Optional (java.util.Optional)10 HttpServletResponse (javax.servlet.http.HttpServletResponse)10 MockServletContext (org.apereo.cas.util.MockServletContext)10