Search in sources :

Example 61 with JEEContext

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

the class AccepttoMultifactorValidateChannelActionTests method verifyOperation.

@Test
public void verifyOperation() throws Exception {
    val httpRequest = new MockHttpServletRequest();
    httpRequest.setRemoteAddr("185.86.151.11");
    httpRequest.setLocalAddr("185.88.151.11");
    ClientInfoHolder.setClientInfo(new ClientInfo(httpRequest));
    val data = MAPPER.writeValueAsString(CollectionUtils.wrap("channel", "test-channel", "status", "approved", "device_id", "deviceid-123456"));
    try (val webServer = new MockWebServer(5001, new ByteArrayResource(data.getBytes(StandardCharsets.UTF_8), "Output"), HttpStatus.OK)) {
        webServer.start();
        val action = new AccepttoMultifactorValidateChannelAction(mfaAccepttoDistributedSessionStore, authenticationSystemSupport);
        val context = new MockRequestContext();
        val request = new MockHttpServletRequest();
        val response = new MockHttpServletResponse();
        val webContext = new JEEContext(request, response);
        context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, response));
        val authn = CoreAuthenticationTestUtils.getAuthentication("casuser");
        WebUtils.putAuthentication(authn, context);
        AccepttoWebflowUtils.storeChannelInSessionStore("test-channel", webContext, mfaAccepttoDistributedSessionStore);
        AccepttoWebflowUtils.storeAuthenticationInSessionStore(authn, webContext, mfaAccepttoDistributedSessionStore);
        RequestContextHolder.setRequestContext(context);
        val result = action.doExecute(context);
        assertEquals(CasWebflowConstants.TRANSITION_ID_FINALIZE, result.getId());
    }
}
Also used : lombok.val(lombok.val) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) ServletExternalContext(org.springframework.webflow.context.servlet.ServletExternalContext) MockWebServer(org.apereo.cas.util.MockWebServer) JEEContext(org.pac4j.core.context.JEEContext) ClientInfo(org.apereo.inspektr.common.web.ClientInfo) ByteArrayResource(org.springframework.core.io.ByteArrayResource) MockRequestContext(org.springframework.webflow.test.MockRequestContext) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) MockServletContext(org.springframework.mock.web.MockServletContext) Test(org.junit.jupiter.api.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 62 with JEEContext

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

the class AccepttoMultifactorValidateChannelAction method doExecute.

@Override
protected Event doExecute(final RequestContext requestContext) {
    val eventAttributes = new LocalAttributeMap<>();
    try {
        val request = WebUtils.getHttpServletRequestFromExternalWebflowContext(requestContext);
        val response = WebUtils.getHttpServletResponseFromExternalWebflowContext(requestContext);
        val webContext = new JEEContext(request, response);
        val channel = AccepttoWebflowUtils.getChannel(webContext, sessionStore);
        if (channel.isEmpty()) {
            LOGGER.debug("Unable to determine channel from session store; not a validation attempt");
            return null;
        }
        val authentication = AccepttoWebflowUtils.getAuthentication(webContext, sessionStore);
        if (authentication == null) {
            LOGGER.debug("Unable to determine the original authentication attempt the session store");
            throw new AuthenticationException("Unable to determine authentication from session store");
        }
        WebUtils.putAuthentication(authentication, requestContext);
        val credential = new AccepttoMultifactorTokenCredential(channel.toString());
        val service = WebUtils.getService(requestContext);
        LOGGER.debug("Cleaning up session store to remove [{}]", credential);
        AccepttoWebflowUtils.resetChannelAndAuthentication(webContext, sessionStore);
        AccepttoWebflowUtils.setChannel(requestContext, null);
        LOGGER.debug("Attempting to authenticate channel [{}] with authentication [{}] and service [{}]", credential, authentication, service);
        var resultBuilder = authenticationSystemSupport.establishAuthenticationContextFromInitial(authentication);
        resultBuilder = authenticationSystemSupport.handleAuthenticationTransaction(service, resultBuilder, credential);
        WebUtils.putAuthenticationResultBuilder(resultBuilder, requestContext);
        return new EventFactorySupport().event(this, CasWebflowConstants.TRANSITION_ID_FINALIZE);
    } catch (final Exception e) {
        eventAttributes.put("error", e);
        LoggingUtils.error(LOGGER, e);
    }
    return new EventFactorySupport().event(this, CasWebflowConstants.TRANSITION_ID_AUTHENTICATION_FAILURE, eventAttributes);
}
Also used : lombok.val(lombok.val) LocalAttributeMap(org.springframework.webflow.core.collection.LocalAttributeMap) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) JEEContext(org.pac4j.core.context.JEEContext) AccepttoMultifactorTokenCredential(org.apereo.cas.mfa.accepto.AccepttoMultifactorTokenCredential) EventFactorySupport(org.springframework.webflow.action.EventFactorySupport) AuthenticationException(org.apereo.cas.authentication.AuthenticationException)

Example 63 with JEEContext

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

the class OAuth20IntrospectionEndpointController method handlePostRequest.

/**
 * Handle post request.
 *
 * @param request  the request
 * @param response the response
 * @return the response entity
 */
@PostMapping(consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE, value = '/' + OAuth20Constants.BASE_OAUTH20_URL + '/' + OAuth20Constants.INTROSPECTION_URL)
public ResponseEntity<OAuth20IntrospectionAccessTokenResponse> handlePostRequest(final HttpServletRequest request, final HttpServletResponse response) {
    ResponseEntity<OAuth20IntrospectionAccessTokenResponse> result;
    try {
        val authExtractor = new BasicAuthExtractor();
        val context = new JEEContext(request, response);
        val credentialsResult = authExtractor.extract(context, getConfigurationContext().getSessionStore());
        if (credentialsResult.isEmpty()) {
            LOGGER.warn("Unable to locate and extract credentials from the request");
            return buildUnauthorizedResponseEntity(OAuth20Constants.INVALID_CLIENT, true);
        }
        val credentials = (UsernamePasswordCredentials) credentialsResult.get();
        val service = OAuth20Utils.getRegisteredOAuthServiceByClientId(getConfigurationContext().getServicesManager(), credentials.getUsername());
        if (service == null) {
            LOGGER.warn("Unable to locate service definition by client id [{}]", credentials.getUsername());
            return buildUnauthorizedResponseEntity(OAuth20Constants.INVALID_CLIENT, true);
        }
        val validationError = validateIntrospectionRequest(service, credentials, request);
        if (validationError.isPresent()) {
            result = validationError.get();
        } else {
            val accessToken = StringUtils.defaultIfBlank(request.getParameter(OAuth20Constants.TOKEN), request.getParameter(OAuth20Constants.ACCESS_TOKEN));
            LOGGER.debug("Located access token [{}] in the request", accessToken);
            var ticket = (OAuth20AccessToken) null;
            try {
                val token = extractAccessTokenFrom(accessToken);
                ticket = getConfigurationContext().getCentralAuthenticationService().getTicket(token, OAuth20AccessToken.class);
            } catch (final InvalidTicketException e) {
                LOGGER.trace(e.getMessage(), e);
                LOGGER.info("Unable to fetch access token [{}]: [{}]", accessToken, e.getMessage());
            }
            val introspect = createIntrospectionValidResponse(ticket);
            result = new ResponseEntity<>(introspect, HttpStatus.OK);
        }
    } catch (final Exception e) {
        LoggingUtils.error(LOGGER, e);
        result = new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
    return result;
}
Also used : lombok.val(lombok.val) OAuth20AccessToken(org.apereo.cas.ticket.accesstoken.OAuth20AccessToken) BasicAuthExtractor(org.pac4j.core.credentials.extractor.BasicAuthExtractor) ResponseEntity(org.springframework.http.ResponseEntity) OAuth20IntrospectionAccessTokenResponse(org.apereo.cas.support.oauth.web.response.introspection.OAuth20IntrospectionAccessTokenResponse) InvalidTicketException(org.apereo.cas.ticket.InvalidTicketException) JEEContext(org.pac4j.core.context.JEEContext) InvalidTicketException(org.apereo.cas.ticket.InvalidTicketException) UsernamePasswordCredentials(org.pac4j.core.credentials.UsernamePasswordCredentials) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 64 with JEEContext

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

the class OAuth20HandlerInterceptorAdapter method requestRequiresAuthentication.

/**
 * Request requires authentication.
 *
 * @param request  the request
 * @param response the response
 * @return true/false
 */
protected boolean requestRequiresAuthentication(final HttpServletRequest request, final HttpServletResponse response) {
    val context = new JEEContext(request, response);
    val revokeTokenRequest = isRevokeTokenRequest(request, response);
    if (revokeTokenRequest) {
        return clientNeedAuthentication(request, response);
    }
    val accessTokenRequest = isAccessTokenRequest(request, response);
    val extractor = extractAccessTokenGrantRequest(context);
    if (!accessTokenRequest) {
        if (extractor.isPresent()) {
            val ext = extractor.get();
            return ext.requestMustBeAuthenticated();
        }
    } else {
        if (extractor.isPresent()) {
            val ext = extractor.get();
            return ext.getResponseType() != OAuth20ResponseTypes.DEVICE_CODE;
        }
    }
    return false;
}
Also used : lombok.val(lombok.val) JEEContext(org.pac4j.core.context.JEEContext)

Example 65 with JEEContext

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

the class OAuth20HandlerInterceptorAdapter method clientNeedAuthentication.

/**
 * Is the client requesting is a OAuth "public" client?
 * An OAuth "public" client is one that does not define a secret like a mobile application.
 *
 * @param request  the request
 * @param response the response
 * @return true/false
 */
protected boolean clientNeedAuthentication(final HttpServletRequest request, final HttpServletResponse response) {
    val clientId = OAuth20Utils.getClientIdAndClientSecret(new JEEContext(request, response), this.sessionStore.getObject()).getLeft();
    if (clientId.isEmpty()) {
        return true;
    }
    val registeredService = OAuth20Utils.getRegisteredOAuthServiceByClientId(servicesManager.getObject(), clientId);
    return registeredService == null || OAuth20Utils.doesServiceNeedAuthentication(registeredService);
}
Also used : lombok.val(lombok.val) JEEContext(org.pac4j.core.context.JEEContext)

Aggregations

JEEContext (org.pac4j.core.context.JEEContext)222 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)27 UsernamePasswordCredentials (org.pac4j.core.credentials.UsernamePasswordCredentials)24 CommonProfile (org.pac4j.core.profile.CommonProfile)21 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)16 HashMap (java.util.HashMap)15 RedirectView (org.springframework.web.servlet.view.RedirectView)14 HttpServletRequest (javax.servlet.http.HttpServletRequest)13 HttpServletResponse (javax.servlet.http.HttpServletResponse)13 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