Search in sources :

Example 26 with WebContext

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);
}
Also used : WebContext(org.pac4j.core.context.WebContext) PlainJWT(com.nimbusds.jwt.PlainJWT) JWT(com.nimbusds.jwt.JWT) SignedJWT(com.nimbusds.jwt.SignedJWT) Test(org.junit.Test)

Example 27 with WebContext

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();
}
Also used : WebContext(org.pac4j.core.context.WebContext) HttpSession(javax.servlet.http.HttpSession) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) HttpServletResponse(javax.servlet.http.HttpServletResponse) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) WebApplicationService(org.apereo.cas.authentication.principal.WebApplicationService) Service(org.apereo.cas.authentication.principal.Service) BaseClient(org.pac4j.core.client.BaseClient) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult) HttpServletRequest(javax.servlet.http.HttpServletRequest) ClientCredential(org.apereo.cas.authentication.principal.ClientCredential) CommonProfile(org.pac4j.core.profile.CommonProfile) ExternalContext(org.springframework.webflow.context.ExternalContext) Credentials(org.pac4j.core.credentials.Credentials)

Example 28 with WebContext

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));
}
Also used : WebContext(org.pac4j.core.context.WebContext) AuthenticationSystemSupport(org.apereo.cas.authentication.AuthenticationSystemSupport) AuthenticationTransactionManager(org.apereo.cas.authentication.AuthenticationTransactionManager) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) FacebookClient(org.pac4j.oauth.client.FacebookClient) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) Service(org.apereo.cas.authentication.principal.Service) MockRequestContext(org.springframework.webflow.test.MockRequestContext) Clients(org.pac4j.core.client.Clients) AuthenticationResultBuilder(org.apereo.cas.authentication.AuthenticationResultBuilder) ExpirationPolicy(org.apereo.cas.ticket.ExpirationPolicy) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult) AuthenticationManager(org.apereo.cas.authentication.AuthenticationManager) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) ServletExternalContext(org.springframework.webflow.context.servlet.ServletExternalContext) Authentication(org.apereo.cas.authentication.Authentication) OAuth20Credentials(org.pac4j.oauth.credentials.OAuth20Credentials) MutableAttributeMap(org.springframework.webflow.core.collection.MutableAttributeMap) MockHttpSession(org.springframework.mock.web.MockHttpSession) Event(org.springframework.webflow.execution.Event) TicketGrantingTicketImpl(org.apereo.cas.ticket.TicketGrantingTicketImpl) AuthenticationTransaction(org.apereo.cas.authentication.AuthenticationTransaction) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.Test)

Example 29 with WebContext

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;
}
Also used : BasicAuthExtractor(org.pac4j.core.credentials.extractor.BasicAuthExtractor) WebContext(org.pac4j.core.context.WebContext) UsernamePasswordCredential(org.apereo.cas.authentication.UsernamePasswordCredential) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) UsernamePasswordCredentials(org.pac4j.core.credentials.UsernamePasswordCredentials)

Example 30 with WebContext

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);
        });
    }
}
Also used : Types(ratpack.util.Types) Context(ratpack.handling.Context) RatpackPac4j(ratpack.pac4j.RatpackPac4j) Exceptions.uncheck(ratpack.util.Exceptions.uncheck) Promise(ratpack.exec.Promise) PublicAddress(ratpack.server.PublicAddress) Blocking(ratpack.exec.Blocking) RequiresHttpAction(org.pac4j.core.exception.RequiresHttpAction) WebContext(org.pac4j.core.context.WebContext) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) Clients(org.pac4j.core.client.Clients) Client(org.pac4j.core.client.Client) Handler(ratpack.handling.Handler) Registry(ratpack.registry.Registry) Optional(java.util.Optional) PathBinding(ratpack.path.PathBinding) TechnicalException(org.pac4j.core.exception.TechnicalException) UserProfile(org.pac4j.core.profile.UserProfile) SessionData(ratpack.session.SessionData) Credentials(org.pac4j.core.credentials.Credentials) Types(ratpack.util.Types) RequiresHttpAction(org.pac4j.core.exception.RequiresHttpAction) TechnicalException(org.pac4j.core.exception.TechnicalException) UserProfile(org.pac4j.core.profile.UserProfile) SessionData(ratpack.session.SessionData) Registry(ratpack.registry.Registry) PathBinding(ratpack.path.PathBinding) Credentials(org.pac4j.core.credentials.Credentials)

Aggregations

WebContext (org.pac4j.core.context.WebContext)58 Test (org.junit.Test)31 MockWebContext (org.pac4j.core.context.MockWebContext)15 Slf4j (lombok.extern.slf4j.Slf4j)11 J2EContext (org.pac4j.core.context.J2EContext)11 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)11 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)11 lombok.val (lombok.val)10 CommonProfile (org.pac4j.core.profile.CommonProfile)10 RedirectAction (org.pac4j.core.redirect.RedirectAction)10 Optional (java.util.Optional)9 Clients (org.pac4j.core.client.Clients)9 SessionStore (org.pac4j.core.context.session.SessionStore)8 JWT (com.nimbusds.jwt.JWT)7 HttpServletRequest (javax.servlet.http.HttpServletRequest)7 Client (org.pac4j.core.client.Client)7 MockIndirectClient (org.pac4j.core.client.MockIndirectClient)7 UserProfile (org.pac4j.core.profile.UserProfile)7 SignedJWT (com.nimbusds.jwt.SignedJWT)6 StringUtils (org.apache.commons.lang3.StringUtils)6