use of org.pac4j.core.context.WebContext in project ddf by codice.
the class OidcTokenValidatorTest method testValidateIdTokensInvalidNonce.
@Test(expected = OidcValidationException.class)
public void testValidateIdTokensInvalidNonce() throws Exception {
WebContext context = getWebContext();
String stringJwt = getIdTokenBuilder().withClaim("nonce", "WRONG").sign(validAlgorithm);
JWT jwt = SignedJWT.parse(stringJwt);
OidcTokenValidator.validateIdTokens(jwt, context, configuration, oidcClient);
}
use of org.pac4j.core.context.WebContext in project cas by apereo.
the class DelegatedClientAuthenticationAction method doExecute.
@Override
protected Event doExecute(final RequestContext context) throws Exception {
final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
final HttpServletResponse response = WebUtils.getHttpServletResponse(context);
final HttpSession session = request.getSession();
// web context
final WebContext webContext = WebUtils.getPac4jJ2EContext(request, response);
// get client
final String clientName = request.getParameter(this.clients.getClientNameParameter());
LOGGER.debug("clientName: [{}]", clientName);
if (hasDelegationRequestFailed(request, response.getStatus()).isPresent()) {
return stopWebflow();
}
// it's an authentication
if (StringUtils.isNotBlank(clientName)) {
// get client
final BaseClient<Credentials, CommonProfile> client = (BaseClient<Credentials, CommonProfile>) this.clients.findClient(clientName);
LOGGER.debug("Client: [{}]", client);
// get credentials
final Credentials credentials;
try {
credentials = client.getCredentials(webContext);
LOGGER.debug("Retrieved credentials: [{}]", credentials);
} catch (final Exception e) {
LOGGER.debug("The request requires http action", e);
return stopWebflow();
}
// retrieve parameters from web session
final Service service = (Service) session.getAttribute(CasProtocolConstants.PARAMETER_SERVICE);
context.getFlowScope().put(CasProtocolConstants.PARAMETER_SERVICE, service);
LOGGER.debug("Retrieve service: [{}]", service);
if (service != null) {
request.setAttribute(CasProtocolConstants.PARAMETER_SERVICE, service.getId());
}
restoreRequestAttribute(request, session, this.themeParamName);
restoreRequestAttribute(request, session, this.localParamName);
restoreRequestAttribute(request, session, CasProtocolConstants.PARAMETER_METHOD);
// credentials not null -> try to authenticate
if (credentials != null) {
final AuthenticationResult authenticationResult = this.authenticationSystemSupport.handleAndFinalizeSingleAuthenticationTransaction(service, new ClientCredential(credentials));
final TicketGrantingTicket tgt = this.centralAuthenticationService.createTicketGrantingTicket(authenticationResult);
WebUtils.putTicketGrantingTicketInScopes(context, tgt);
return success();
}
}
// no or aborted authentication : go to login page
prepareForLoginPage(context);
if (response.getStatus() == HttpStatus.UNAUTHORIZED.value()) {
return stopWebflow();
}
if (this.autoRedirect) {
final Set<ProviderLoginPageConfiguration> urls = context.getFlowScope().get(PAC4J_URLS, Set.class);
if (urls != null && urls.size() == 1) {
final ProviderLoginPageConfiguration cfg = urls.stream().findFirst().get();
LOGGER.debug("Auto-redirecting to client url [{}]", cfg.getRedirectUrl());
response.sendRedirect(cfg.getRedirectUrl());
final ExternalContext externalContext = context.getExternalContext();
externalContext.recordResponseComplete();
return stopWebflow();
}
}
return error();
}
use of org.pac4j.core.context.WebContext in project cas by apereo.
the class DelegatedClientAuthenticationActionTests method verifyFinishAuthentication.
@Test
public void verifyFinishAuthentication() throws Exception {
final MockHttpServletRequest mockRequest = new MockHttpServletRequest();
mockRequest.setParameter(Clients.DEFAULT_CLIENT_NAME_PARAMETER, "FacebookClient");
final MockHttpSession mockSession = new MockHttpSession();
mockSession.setAttribute(ThemeChangeInterceptor.DEFAULT_PARAM_NAME, MY_THEME);
mockSession.setAttribute(LocaleChangeInterceptor.DEFAULT_PARAM_NAME, MY_LOCALE);
mockSession.setAttribute(CasProtocolConstants.PARAMETER_METHOD, MY_METHOD);
final Service service = CoreAuthenticationTestUtils.getService(MY_SERVICE);
mockSession.setAttribute(CasProtocolConstants.PARAMETER_SERVICE, service);
mockRequest.setSession(mockSession);
final ServletExternalContext servletExternalContext = mock(ServletExternalContext.class);
when(servletExternalContext.getNativeRequest()).thenReturn(mockRequest);
when(servletExternalContext.getNativeResponse()).thenReturn(new MockHttpServletResponse());
final MockRequestContext mockRequestContext = new MockRequestContext();
mockRequestContext.setExternalContext(servletExternalContext);
final FacebookClient facebookClient = new FacebookClient() {
@Override
protected OAuth20Credentials retrieveCredentials(final WebContext context) throws HttpAction {
return new OAuth20Credentials("fakeVerifier", FacebookClient.class.getSimpleName());
}
};
facebookClient.setName(FacebookClient.class.getSimpleName());
final Clients clients = new Clients(MY_LOGIN_URL, facebookClient);
final TicketGrantingTicket tgt = new TicketGrantingTicketImpl(TGT_ID, mock(Authentication.class), mock(ExpirationPolicy.class));
final CentralAuthenticationService casImpl = mock(CentralAuthenticationService.class);
when(casImpl.createTicketGrantingTicket(any(AuthenticationResult.class))).thenReturn(tgt);
final AuthenticationTransactionManager transManager = mock(AuthenticationTransactionManager.class);
final AuthenticationManager authNManager = mock(AuthenticationManager.class);
when(authNManager.authenticate(any(AuthenticationTransaction.class))).thenReturn(CoreAuthenticationTestUtils.getAuthentication());
when(transManager.getAuthenticationManager()).thenReturn(authNManager);
when(transManager.handle(any(AuthenticationTransaction.class), any(AuthenticationResultBuilder.class))).thenReturn(transManager);
final AuthenticationSystemSupport support = mock(AuthenticationSystemSupport.class);
when(support.getAuthenticationTransactionManager()).thenReturn(transManager);
final DelegatedClientAuthenticationAction action = new DelegatedClientAuthenticationAction(clients, support, casImpl, "theme", "locale", false);
final Event event = action.execute(mockRequestContext);
assertEquals("success", event.getId());
assertEquals(MY_THEME, mockRequest.getAttribute(ThemeChangeInterceptor.DEFAULT_PARAM_NAME));
assertEquals(MY_LOCALE, mockRequest.getAttribute(LocaleChangeInterceptor.DEFAULT_PARAM_NAME));
assertEquals(MY_METHOD, mockRequest.getAttribute(CasProtocolConstants.PARAMETER_METHOD));
assertEquals(MY_SERVICE, mockRequest.getAttribute(CasProtocolConstants.PARAMETER_SERVICE));
final MutableAttributeMap flowScope = mockRequestContext.getFlowScope();
final MutableAttributeMap requestScope = mockRequestContext.getRequestScope();
assertEquals(service, flowScope.get(CasProtocolConstants.PARAMETER_SERVICE));
assertEquals(TGT_ID, flowScope.get(TGT_NAME));
assertEquals(TGT_ID, requestScope.get(TGT_NAME));
}
use of org.pac4j.core.context.WebContext in project cas by apereo.
the class ECPProfileHandlerController method extractBasicAuthenticationCredential.
private Credential extractBasicAuthenticationCredential(final HttpServletRequest request, final HttpServletResponse response) {
try {
final BasicAuthExtractor extractor = new BasicAuthExtractor(this.getClass().getSimpleName());
final WebContext webContext = WebUtils.getPac4jJ2EContext(request, response);
final UsernamePasswordCredentials credentials = extractor.extract(webContext);
if (credentials != null) {
LOGGER.debug("Received basic authentication ECP request from credentials [{}]", credentials);
return new UsernamePasswordCredential(credentials.getUsername(), credentials.getPassword());
}
} catch (final Exception e) {
LOGGER.warn(e.getMessage(), e);
}
return null;
}
use of org.pac4j.core.context.WebContext in project ratpack by ratpack.
the class Pac4jAuthenticator method handle.
@Override
public void handle(Context ctx) throws Exception {
PathBinding pathBinding = ctx.getPathBinding();
String pastBinding = pathBinding.getPastBinding();
if (pastBinding.equals(path)) {
RatpackWebContext.from(ctx, true).flatMap(webContext -> {
SessionData sessionData = webContext.getSession();
return createClients(ctx, pathBinding).map(clients -> clients.findClient(webContext)).map(Types::<Client<Credentials, UserProfile>>cast).flatMap(client -> getProfile(webContext, client)).map(profile -> {
if (profile != null) {
sessionData.set(Pac4jSessionKeys.USER_PROFILE, profile);
}
Optional<String> originalUrl = sessionData.get(Pac4jSessionKeys.REQUESTED_URL);
sessionData.remove(Pac4jSessionKeys.REQUESTED_URL);
return originalUrl;
}).onError(t -> {
if (t instanceof RequiresHttpAction) {
webContext.sendResponse((RequiresHttpAction) t);
} else {
ctx.error(new TechnicalException("Failed to get user profile", t));
}
});
}).then(originalUrlOption -> {
ctx.redirect(originalUrlOption.orElse("/"));
});
} else {
createClients(ctx, pathBinding).then(clients -> {
Registry registry = Registry.singleLazy(Clients.class, () -> uncheck(() -> clients));
ctx.next(registry);
});
}
}
Aggregations