Search in sources :

Example 16 with WebContext

use of org.pac4j.core.context.WebContext in project pac4j by pac4j.

the class CasClientTests method testCallbackUrlResolver.

@Test
public void testCallbackUrlResolver() {
    final CasConfiguration configuration = new CasConfiguration();
    configuration.setPrefixUrl(CAS);
    configuration.setLoginUrl(CAS + LOGIN);
    final CasClient casClient = new CasClient(configuration);
    casClient.setCallbackUrl(CASBACK);
    casClient.setUrlResolver((url, context) -> HOST + url);
    casClient.setCallbackUrlResolver(new CallbackUrlResolver() {

        @Override
        public String compute(final UrlResolver urlResolver, final String url, final String clientName, final WebContext context) {
            return null;
        }

        @Override
        public boolean matches(final String clientName, final WebContext context) {
            return false;
        }
    });
    casClient.init();
    assertEquals(HOST + CAS + LOGIN, configuration.computeFinalLoginUrl(null));
    assertEquals(HOST + CAS + "/", configuration.computeFinalPrefixUrl(null));
}
Also used : UrlResolver(org.pac4j.core.http.url.UrlResolver) CallbackUrlResolver(org.pac4j.core.http.callback.CallbackUrlResolver) WebContext(org.pac4j.core.context.WebContext) MockWebContext(org.pac4j.core.context.MockWebContext) CasConfiguration(org.pac4j.cas.config.CasConfiguration) CallbackUrlResolver(org.pac4j.core.http.callback.CallbackUrlResolver) Test(org.junit.Test)

Example 17 with WebContext

use of org.pac4j.core.context.WebContext in project druid by druid-io.

the class Pac4jSessionStoreTest method testSetAndGet.

@Test
public void testSetAndGet() {
    Pac4jSessionStore<WebContext> sessionStore = new Pac4jSessionStore("test-cookie-passphrase");
    WebContext webContext1 = EasyMock.mock(WebContext.class);
    EasyMock.expect(webContext1.getScheme()).andReturn("https");
    Capture<Cookie> cookieCapture = EasyMock.newCapture();
    webContext1.addResponseCookie(EasyMock.capture(cookieCapture));
    EasyMock.replay(webContext1);
    sessionStore.set(webContext1, "key", "value");
    Cookie cookie = cookieCapture.getValue();
    Assert.assertTrue(cookie.isSecure());
    Assert.assertTrue(cookie.isHttpOnly());
    Assert.assertTrue(cookie.isSecure());
    Assert.assertEquals(900, cookie.getMaxAge());
    WebContext webContext2 = EasyMock.mock(WebContext.class);
    EasyMock.expect(webContext2.getRequestCookies()).andReturn(Collections.singletonList(cookie));
    EasyMock.replay(webContext2);
    Assert.assertEquals("value", sessionStore.get(webContext2, "key"));
}
Also used : Cookie(org.pac4j.core.context.Cookie) WebContext(org.pac4j.core.context.WebContext) Test(org.junit.Test)

Example 18 with WebContext

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

the class OidcPrivateKeyJwtAuthenticator method validate.

@Override
public void validate(final Credentials creds, final WebContext webContext, final SessionStore sessionStore) {
    val credentials = (UsernamePasswordCredentials) creds;
    val registeredService = verifyCredentials(credentials, webContext);
    if (registeredService == null) {
        LOGGER.warn("Unable to verify credentials");
        return;
    }
    val clientId = registeredService.getClientId();
    val audience = casProperties.getServer().getPrefix().concat('/' + OidcConstants.BASE_OIDC_URL + '/' + OidcConstants.ACCESS_TOKEN_URL);
    val keys = OidcJsonWebKeyStoreUtils.getJsonWebKeySet(registeredService, applicationContext, Optional.of(OidcJsonWebKeyUsage.SIGNING));
    keys.ifPresent(Unchecked.consumer(jwks -> jwks.getJsonWebKeys().forEach(jsonWebKey -> {
        val consumer = new JwtConsumerBuilder().setVerificationKey(jsonWebKey.getKey()).setRequireSubject().setExpectedSubject(clientId).setRequireJwtId().setRequireExpirationTime().setExpectedIssuer(true, clientId).setExpectedAudience(true, audience).build();
        determineUserProfile(credentials, consumer);
    })));
}
Also used : lombok.val(lombok.val) CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) UsernamePasswordCredentials(org.pac4j.core.credentials.UsernamePasswordCredentials) Unchecked(org.jooq.lambda.Unchecked) CommonProfile(org.pac4j.core.profile.CommonProfile) SneakyThrows(lombok.SneakyThrows) OidcConstants(org.apereo.cas.oidc.OidcConstants) lombok.val(lombok.val) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) SessionStore(org.pac4j.core.context.session.SessionStore) ApplicationContext(org.springframework.context.ApplicationContext) WebApplicationService(org.apereo.cas.authentication.principal.WebApplicationService) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) WebContext(org.pac4j.core.context.WebContext) Slf4j(lombok.extern.slf4j.Slf4j) AuditableExecution(org.apereo.cas.audit.AuditableExecution) TicketRegistry(org.apereo.cas.ticket.registry.TicketRegistry) OidcJsonWebKeyStoreUtils(org.apereo.cas.oidc.jwks.OidcJsonWebKeyStoreUtils) Optional(java.util.Optional) Credentials(org.pac4j.core.credentials.Credentials) ServiceFactory(org.apereo.cas.authentication.principal.ServiceFactory) Algorithm(com.nimbusds.jose.Algorithm) OidcJsonWebKeyUsage(org.apereo.cas.oidc.jwks.OidcJsonWebKeyUsage) ServicesManager(org.apereo.cas.services.ServicesManager) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) UsernamePasswordCredentials(org.pac4j.core.credentials.UsernamePasswordCredentials)

Example 19 with WebContext

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

the class SamlIdPUtils method retrieveSamlRequest.

/**
 * Retrieve authn request authn request.
 *
 * @param context            the context
 * @param sessionStore       the session store
 * @param openSamlConfigBean the open saml config bean
 * @param clazz              the clazz
 * @return the request
 */
public static Optional<Pair<? extends RequestAbstractType, MessageContext>> retrieveSamlRequest(final WebContext context, final SessionStore sessionStore, final OpenSamlConfigBean openSamlConfigBean, final Class<? extends RequestAbstractType> clazz) {
    LOGGER.trace("Retrieving authentication request from scope");
    val authnContext = sessionStore.get(context, SamlProtocolConstants.PARAMETER_SAML_REQUEST).map(String.class::cast).map(value -> retrieveSamlRequest(openSamlConfigBean, clazz, value)).flatMap(authnRequest -> sessionStore.get(context, MessageContext.class.getName()).map(String.class::cast).map(result -> SamlIdPAuthenticationContext.decode(result).toMessageContext(authnRequest)));
    return authnContext.map(ctx -> Pair.of((AuthnRequest) ctx.getMessage(), ctx));
}
Also used : lombok.val(lombok.val) MessageContext(org.opensaml.messaging.context.MessageContext) SneakyThrows(lombok.SneakyThrows) Inflater(java.util.zip.Inflater) SamlIdPAuthenticationContext(org.apereo.cas.support.saml.authentication.SamlIdPAuthenticationContext) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) StringUtils(org.apache.commons.lang3.StringUtils) LogoutRequest(org.opensaml.saml.saml2.core.LogoutRequest) StatusResponseType(org.opensaml.saml.saml2.core.StatusResponseType) FunctionUtils(org.apereo.cas.util.function.FunctionUtils) SAMLBindingSupport(org.opensaml.saml.common.binding.SAMLBindingSupport) Pair(org.apache.commons.lang3.tuple.Pair) ByteArrayInputStream(java.io.ByteArrayInputStream) AssertionConsumerServiceBuilder(org.opensaml.saml.saml2.metadata.impl.AssertionConsumerServiceBuilder) Unchecked(org.jooq.lambda.Unchecked) SignableSAMLObject(org.opensaml.saml.common.SignableSAMLObject) AssertionConsumerService(org.opensaml.saml.saml2.metadata.AssertionConsumerService) Base64Support(net.shibboleth.utilities.java.support.codec.Base64Support) MetadataResolver(org.opensaml.saml.metadata.resolver.MetadataResolver) RequestAbstractType(org.opensaml.saml.saml2.core.RequestAbstractType) SessionStore(org.pac4j.core.context.session.SessionStore) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Objects(java.util.Objects) Slf4j(lombok.extern.slf4j.Slf4j) SAMLObject(org.opensaml.saml.common.SAMLObject) SamlRegisteredServiceServiceProviderMetadataFacade(org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade) CriteriaSet(net.shibboleth.utilities.java.support.resolver.CriteriaSet) SAMLPeerEntityContext(org.opensaml.saml.common.messaging.context.SAMLPeerEntityContext) Optional(java.util.Optional) EncodingUtils(org.apereo.cas.util.EncodingUtils) InflaterInputStream(java.util.zip.InflaterInputStream) SamlRegisteredServiceCachingMetadataResolver(org.apereo.cas.support.saml.services.idp.metadata.cache.SamlRegisteredServiceCachingMetadataResolver) XMLObjectSupport(org.opensaml.core.xml.util.XMLObjectSupport) UtilityClass(lombok.experimental.UtilityClass) WebContext(org.pac4j.core.context.WebContext) SamlRegisteredService(org.apereo.cas.support.saml.services.SamlRegisteredService) SamlIdPSamlRegisteredServiceCriterion(org.apereo.cas.support.saml.idp.metadata.locator.SamlIdPSamlRegisteredServiceCriterion) Assertion(org.opensaml.saml.saml2.core.Assertion) RoleDescriptorResolver(org.opensaml.saml.metadata.resolver.RoleDescriptorResolver) IDPSSODescriptor(org.opensaml.saml.saml2.metadata.IDPSSODescriptor) JEEContext(org.pac4j.core.context.JEEContext) ServicesManager(org.apereo.cas.services.ServicesManager) lombok.val(lombok.val) PredicateRoleDescriptorResolver(org.opensaml.saml.metadata.resolver.impl.PredicateRoleDescriptorResolver) Endpoint(org.opensaml.saml.saml2.metadata.Endpoint) EvaluableEntityRoleEntityDescriptorCriterion(org.opensaml.saml.metadata.criteria.entity.impl.EvaluableEntityRoleEntityDescriptorCriterion) SAMLEndpointContext(org.opensaml.saml.common.messaging.context.SAMLEndpointContext) ChainingMetadataResolver(org.opensaml.saml.metadata.resolver.ChainingMetadataResolver) NameIDPolicy(org.opensaml.saml.saml2.core.NameIDPolicy) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest)

Example 20 with WebContext

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

the class DistributedJEESessionStore method set.

@Override
public void set(final WebContext context, final String key, final Object value) {
    LOGGER.trace("Setting key: [{}]", key);
    val sessionId = getSessionId(context, true).get();
    val properties = new HashMap<String, Serializable>();
    if (value instanceof Serializable) {
        properties.put(key, (Serializable) value);
    } else if (value != null) {
        LOGGER.warn("Object value [{}] assigned to [{}] is not serializable and may not be part of the ticket [{}]", value, key, sessionId);
    }
    val ticket = getTransientSessionTicketForSession(context);
    if (value == null && ticket != null) {
        ticket.getProperties().remove(key);
        FunctionUtils.doUnchecked(s -> this.centralAuthenticationService.updateTicket(ticket));
    } else if (ticket == null) {
        val transientFactory = (TransientSessionTicketFactory) this.ticketFactory.get(TransientSessionTicket.class);
        val created = transientFactory.create(sessionId, properties);
        FunctionUtils.doUnchecked(s -> this.centralAuthenticationService.addTicket(created));
    } else {
        ticket.getProperties().putAll(properties);
        FunctionUtils.doUnchecked(s -> this.centralAuthenticationService.updateTicket(ticket));
    }
}
Also used : lombok.val(lombok.val) TransientSessionTicket(org.apereo.cas.ticket.TransientSessionTicket) RequiredArgsConstructor(lombok.RequiredArgsConstructor) lombok.val(lombok.val) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) HashMap(java.util.HashMap) UUID(java.util.UUID) StringUtils(org.apache.commons.lang3.StringUtils) SessionStore(org.pac4j.core.context.session.SessionStore) Serializable(java.io.Serializable) WebContext(org.pac4j.core.context.WebContext) FunctionUtils(org.apereo.cas.util.function.FunctionUtils) Slf4j(lombok.extern.slf4j.Slf4j) TransientSessionTicketFactory(org.apereo.cas.ticket.TransientSessionTicketFactory) CasCookieBuilder(org.apereo.cas.web.cookie.CasCookieBuilder) Optional(java.util.Optional) TicketFactory(org.apereo.cas.ticket.TicketFactory) JEEContext(org.pac4j.core.context.JEEContext) Transactional(org.springframework.transaction.annotation.Transactional) Serializable(java.io.Serializable) HashMap(java.util.HashMap)

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