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();
}
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);
}
}
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());
}
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));
}
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());
}
Aggregations