Search in sources :

Example 1 with JEEContext

use of org.pac4j.core.context.JEEContext in project ddf by codice.

the class OidcCallbackEndpoint method logout.

@GET
@Path("/logout")
public Response logout(@Context HttpServletRequest request, @Context HttpServletResponse response) {
    if (request == null) {
        throw new IllegalArgumentException("Passed in request cannot be null.");
    }
    if (response == null) {
        throw new IllegalArgumentException("Passed in response cannot be null.");
    }
    if (request.getSession(false) == null) {
        throw new IllegalArgumentException("Passed in request must have a corresponding session to logout.");
    }
    JEESessionStore sessionStore = new JEESessionStore();
    JEEContext jeeContext = new JEEContext(request, response, sessionStore);
    this.securityLogger.audit("Logging out");
    sessionStore.destroySession(jeeContext);
    String localLogout = SystemBaseUrl.EXTERNAL.constructUrl("/logout/local");
    WebClient webClient = getWebClient(localLogout);
    Response logoutResponse = webClient.get();
    if (logoutResponse.getStatus() == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
        return logoutResponse;
    }
    try {
        String redirectUrl = SystemBaseUrl.EXTERNAL.constructUrl(redirectUri, false);
        URIBuilder redirectUrlBuilder = new URIBuilder(redirectUrl);
        String prevUrl = request.getParameter("prevurl");
        if (prevUrl != null) {
            redirectUrlBuilder.addParameter("prevurl", prevUrl);
        }
        return Response.seeOther(redirectUrlBuilder.build()).build();
    } catch (URISyntaxException e) {
        LOGGER.debug("Unable to create logout response URL for OIDC logout.", e);
    }
    return Response.serverError().build();
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(javax.ws.rs.core.Response) JEEContext(org.pac4j.core.context.JEEContext) JEESessionStore(org.pac4j.core.context.session.JEESessionStore) URISyntaxException(java.net.URISyntaxException) WebClient(org.apache.cxf.jaxrs.client.WebClient) URIBuilder(org.apache.http.client.utils.URIBuilder) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 2 with JEEContext

use of org.pac4j.core.context.JEEContext in project ddf by codice.

the class OidcHandler method getNormalizedToken.

/**
 * Handler implementing OIDC authentication.
 *
 * @param request http request to obtain attributes from and to pass into any local filter chains
 *     required
 * @param response http response to return http responses or redirects
 * @param chain original filter chain (should not be called from your handler)
 * @param resolve flag with true implying that credentials should be obtained, false implying
 *     return if no credentials are found.
 * @return result of handling this request - status and optional tokens
 * @throws AuthenticationFailureException
 */
@Override
public HandlerResult getNormalizedToken(ServletRequest request, ServletResponse response, SecurityFilterChain chain, boolean resolve) throws AuthenticationFailureException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    if (httpRequest.getMethod().equals("HEAD")) {
        return processHeadRequest(httpResponse);
    }
    LOGGER.debug("Doing Oidc authentication and authorization for path {}.", httpRequest.getContextPath());
    JEESessionStore sessionStore = new JEESessionStore();
    JEEContext jeeContext = new JEEContext(httpRequest, httpResponse, sessionStore);
    StringBuffer requestUrlBuffer = httpRequest.getRequestURL();
    requestUrlBuffer.append(httpRequest.getQueryString() == null ? "" : "?" + httpRequest.getQueryString());
    String requestUrl = requestUrlBuffer.toString();
    String ipAddress = httpRequest.getRemoteAddr();
    OidcClient<OidcConfiguration> oidcClient = configuration.getOidcClient(requestUrl);
    OidcCredentials credentials;
    boolean isMachine = userAgentIsNotBrowser(httpRequest);
    if (isMachine) {
        LOGGER.debug("The Oidc Handler does not handle machine to machine requests. Continuing to other handlers.");
        return noActionResult;
    } else {
        // check for Authorization Code Flow, Implicit Flow, or Hybrid Flow credentials
        try {
            credentials = getCredentialsFromRequest(oidcClient, jeeContext);
        } catch (IllegalArgumentException e) {
            LOGGER.debug(e.getMessage(), e);
            LOGGER.error("Problem with the Oidc Handler's configuration. " + "Check the Oidc Handler configuration in the admin console.");
            return noActionResult;
        } catch (TechnicalException e) {
            LOGGER.debug("Problem extracting Oidc credentials from incoming user request.", e);
            return redirectForCredentials(oidcClient, jeeContext, requestUrl);
        }
    }
    // if the request has credentials, process it
    if (credentials != null && (credentials.getCode() != null || credentials.getAccessToken() != null || credentials.getIdToken() != null)) {
        LOGGER.info("Oidc credentials found/retrieved. Saving to session and continuing filter chain.");
        OidcAuthenticationToken token = new OidcAuthenticationToken(credentials, jeeContext, ipAddress);
        HandlerResult handlerResult = new HandlerResultImpl(Status.COMPLETED, token);
        handlerResult.setSource(SOURCE);
        return handlerResult;
    } else {
        // the user agent request didn't have credentials, redirect and go get some
        LOGGER.info("No credentials found on user-agent request. " + "Redirecting user-agent to IdP for credentials.");
        return redirectForCredentials(oidcClient, jeeContext, requestUrl);
    }
}
Also used : TechnicalException(org.pac4j.core.exception.TechnicalException) HandlerResultImpl(org.codice.ddf.security.handler.HandlerResultImpl) JEEContext(org.pac4j.core.context.JEEContext) OidcAuthenticationToken(org.codice.ddf.security.handler.OidcAuthenticationToken) HttpServletResponse(javax.servlet.http.HttpServletResponse) JEESessionStore(org.pac4j.core.context.session.JEESessionStore) HandlerResult(org.codice.ddf.security.handler.api.HandlerResult) HttpServletRequest(javax.servlet.http.HttpServletRequest) OidcConfiguration(org.pac4j.oidc.config.OidcConfiguration) OidcCredentials(org.pac4j.oidc.credentials.OidcCredentials)

Example 3 with JEEContext

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

the class OidcPushedAuthorizationRequestValidatorTests method verifyOperation.

@Test
public void verifyOperation() throws Exception {
    val registeredService = getOidcRegisteredService();
    val profile = new CommonProfile();
    profile.setId("casTest");
    val holder = AccessTokenRequestContext.builder().clientId(registeredService.getClientId()).service(RegisteredServiceTestUtils.getService()).authentication(RegisteredServiceTestUtils.getAuthentication()).registeredService(registeredService).grantType(OAuth20GrantTypes.AUTHORIZATION_CODE).responseType(OAuth20ResponseTypes.CODE).userProfile(profile).build();
    val factory = (OidcPushedAuthorizationRequestFactory) defaultTicketFactory.get(OidcPushedAuthorizationRequest.class);
    val ticket = factory.create(holder);
    assertNotNull(ticket);
    ticketRegistry.addTicket(ticket);
    val request = new MockHttpServletRequest();
    request.addParameter(OAuth20Constants.CLIENT_ID, holder.getClientId());
    request.addParameter(OidcConstants.REQUEST_URI, ticket.getId());
    val context = new JEEContext(request, new MockHttpServletResponse());
    assertTrue(oidcPushedAuthorizationRequestValidator.supports(context));
    assertTrue(oidcPushedAuthorizationRequestValidator.validate(context));
    assertEquals(0, oidcPushedAuthorizationRequestValidator.getOrder());
}
Also used : lombok.val(lombok.val) CommonProfile(org.pac4j.core.profile.CommonProfile) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) JEEContext(org.pac4j.core.context.JEEContext) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 4 with JEEContext

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

the class OidcAccessTokenResponseGeneratorTests method verifyAccessTokenResponseForDeviceCode.

@Test
public void verifyAccessTokenResponseForDeviceCode() {
    val devCode = deviceTokenFactory.createDeviceCode(RegisteredServiceTestUtils.getService());
    val token = OAuth20TokenGeneratedResult.builder().registeredService(getOidcRegisteredService()).responseType(OAuth20ResponseTypes.DEVICE_CODE).deviceCode(devCode.getId()).userCode(deviceUserCodeFactory.createDeviceUserCode(devCode).getId()).build();
    val request = new MockHttpServletRequest();
    val response = new MockHttpServletResponse();
    val context = new JEEContext(request, response);
    val manager = new ProfileManager(context, JEESessionStore.INSTANCE);
    val profile = new CommonProfile();
    profile.setClientName(Authenticators.CAS_OAUTH_CLIENT_BASIC_AUTHN);
    profile.setId("casuser");
    manager.save(true, profile, false);
    val result = OAuth20AccessTokenResponseResult.builder().service(RegisteredServiceTestUtils.getService()).registeredService(getOidcRegisteredService()).casProperties(casProperties).generatedToken(token).responseType(OAuth20ResponseTypes.DEVICE_CODE).userProfile(profile).build();
    val mv = oidcAccessTokenResponseGenerator.generate(result);
    assertNotNull(mv);
    val modelMap = mv.getModelMap();
    assertTrue(modelMap.containsKey(OAuth20Constants.DEVICE_VERIFICATION_URI));
    assertTrue(modelMap.containsKey(OAuth20Constants.DEVICE_USER_CODE));
    assertTrue(modelMap.containsKey(OAuth20Constants.DEVICE_CODE));
    assertTrue(modelMap.containsKey(OAuth20Constants.DEVICE_INTERVAL));
}
Also used : lombok.val(lombok.val) ProfileManager(org.pac4j.core.profile.ProfileManager) CommonProfile(org.pac4j.core.profile.CommonProfile) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) JEEContext(org.pac4j.core.context.JEEContext) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 5 with JEEContext

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

the class OidcAuthenticationAuthorizeSecurityLogicTests method verifyMaxAgeOperation.

@Test
public void verifyMaxAgeOperation() {
    val request = new MockHttpServletRequest();
    request.addParameter(OidcConstants.MAX_AGE, "5");
    val response = new MockHttpServletResponse();
    when(ticketGrantingTicketCookieGenerator.retrieveCookieValue(request)).thenReturn(ticketGrantingTicket.getId());
    val context = new JEEContext(request, response);
    val profileManager = new ProfileManager(context, JEESessionStore.INSTANCE);
    var profile = new BasicUserProfile();
    profile.addAuthenticationAttribute(CasProtocolConstants.VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_AUTHENTICATION_DATE, ZonedDateTime.now(Clock.systemUTC()).minusSeconds(30));
    profileManager.save(true, profile, false);
    val logic = new OidcAuthenticationAuthorizeSecurityLogic(ticketGrantingTicketCookieGenerator, ticketRegistry, centralAuthenticationService);
    assertTrue(logic.loadProfiles(profileManager, context, JEESessionStore.INSTANCE, List.of()).isEmpty());
}
Also used : lombok.val(lombok.val) ProfileManager(org.pac4j.core.profile.ProfileManager) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) JEEContext(org.pac4j.core.context.JEEContext) BasicUserProfile(org.pac4j.core.profile.BasicUserProfile) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

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