Search in sources :

Example 31 with JEEContext

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

the class AuthnRequestRequestedAttributesAttributeReleasePolicyTests method verifyAuthnRequestWithoutExtensions.

@Test
public void verifyAuthnRequestWithoutExtensions() throws IOException {
    val filter = new AuthnRequestRequestedAttributesAttributeReleasePolicy();
    filter.setAllowedAttributes(List.of("eduPersonPrincipalAttribute"));
    filter.setUseFriendlyName(true);
    val registeredService = SamlIdPTestUtils.getSamlRegisteredService();
    registeredService.setAttributeReleasePolicy(filter);
    val builder = new SAML2AuthnRequestBuilder();
    val authnRequest = builder.build(saml2MessageContext);
    try (val writer = SamlUtils.transformSamlObject(openSamlConfigBean, authnRequest)) {
        val samlRequest = EncodingUtils.encodeBase64(writer.toString().getBytes(StandardCharsets.UTF_8));
        val request = HttpRequestUtils.getHttpServletRequestFromRequestAttributes();
        val response = HttpRequestUtils.getHttpServletResponseFromRequestAttributes();
        val context = new JEEContext(request, response);
        samlIdPDistributedSessionStore.set(context, SamlProtocolConstants.PARAMETER_SAML_REQUEST, samlRequest);
        val messageContext = new MessageContext();
        messageContext.setMessage(authnRequest);
        samlIdPDistributedSessionStore.set(context, MessageContext.class.getName(), SamlIdPAuthenticationContext.from(messageContext).encode());
        val releasePolicyContext = RegisteredServiceAttributeReleasePolicyContext.builder().registeredService(registeredService).service(CoreAuthenticationTestUtils.getService()).principal(getPrincipal("casuser", CollectionUtils.wrap("eduPersonPrincipalName", "casuser"))).build();
        val attributes = filter.getAttributes(releasePolicyContext);
        assertTrue(attributes.isEmpty());
    }
}
Also used : lombok.val(lombok.val) JEEContext(org.pac4j.core.context.JEEContext) MessageContext(org.opensaml.messaging.context.MessageContext) SAML2MessageContext(org.pac4j.saml.context.SAML2MessageContext) SAML2AuthnRequestBuilder(org.pac4j.saml.sso.impl.SAML2AuthnRequestBuilder) Test(org.junit.jupiter.api.Test)

Example 32 with JEEContext

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

the class AuthnRequestRequestedAttributesAttributeReleasePolicyTests method verifyAuthnRequestWithExtensionsNotAllowed.

@Test
public void verifyAuthnRequestWithExtensionsNotAllowed() throws IOException {
    val filter = new AuthnRequestRequestedAttributesAttributeReleasePolicy();
    filter.setAllowedAttributes(List.of("eduPersonPrincipalAttribute"));
    filter.setUseFriendlyName(false);
    val registeredService = SamlIdPTestUtils.getSamlRegisteredService();
    registeredService.setAttributeReleasePolicy(filter);
    val builder = new SAML2AuthnRequestBuilder();
    val authnRequest = builder.build(saml2MessageContext);
    val extensions = ((SAMLObjectBuilder<Extensions>) openSamlConfigBean.getBuilderFactory().getBuilder(Extensions.DEFAULT_ELEMENT_NAME)).buildObject();
    val attrBuilder = (SAMLObjectBuilder<RequestedAttribute>) openSamlConfigBean.getBuilderFactory().getBuilder(RequestedAttribute.DEFAULT_ELEMENT_NAME);
    val requestAttribute = attrBuilder.buildObject(RequestedAttribute.DEFAULT_ELEMENT_NAME);
    requestAttribute.setIsRequired(false);
    requestAttribute.setName("givenName");
    extensions.getUnknownXMLObjects().add(requestAttribute);
    authnRequest.setExtensions(extensions);
    try (val writer = SamlUtils.transformSamlObject(openSamlConfigBean, authnRequest)) {
        val samlRequest = EncodingUtils.encodeBase64(writer.toString().getBytes(StandardCharsets.UTF_8));
        val request = HttpRequestUtils.getHttpServletRequestFromRequestAttributes();
        val response = HttpRequestUtils.getHttpServletResponseFromRequestAttributes();
        val context = new JEEContext(request, response);
        samlIdPDistributedSessionStore.set(context, SamlProtocolConstants.PARAMETER_SAML_REQUEST, samlRequest);
        val messageContext = new MessageContext();
        messageContext.setMessage(authnRequest);
        samlIdPDistributedSessionStore.set(context, MessageContext.class.getName(), SamlIdPAuthenticationContext.from(messageContext).encode());
        val releasePolicyContext = RegisteredServiceAttributeReleasePolicyContext.builder().registeredService(registeredService).service(CoreAuthenticationTestUtils.getService()).principal(getPrincipal("casuser", CollectionUtils.wrap("eduPersonPrincipalName", "casuser", "givenName", "CAS"))).build();
        val attributes = filter.getAttributes(releasePolicyContext);
        assertTrue(attributes.isEmpty());
    }
}
Also used : lombok.val(lombok.val) SAMLObjectBuilder(org.opensaml.saml.common.SAMLObjectBuilder) JEEContext(org.pac4j.core.context.JEEContext) MessageContext(org.opensaml.messaging.context.MessageContext) SAML2MessageContext(org.pac4j.saml.context.SAML2MessageContext) SAML2AuthnRequestBuilder(org.pac4j.saml.sso.impl.SAML2AuthnRequestBuilder) Test(org.junit.jupiter.api.Test)

Example 33 with JEEContext

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

the class AuthnRequestRequestedAttributesAttributeReleasePolicyTests method initialize.

@BeforeEach
public void initialize() throws Exception {
    val idpMetadata = new File("src/test/resources/metadata/idp-metadata.xml").getCanonicalPath();
    val keystorePath = new File(FileUtils.getTempDirectory(), "keystore").getCanonicalPath();
    val spMetadataPath = new File(FileUtils.getTempDirectory(), "sp-metadata.xml").getCanonicalPath();
    saml2Configuration = new SAML2Configuration(keystorePath, "changeit", "changeit", idpMetadata);
    saml2Configuration.setServiceProviderEntityId("cas:example:sp");
    saml2Configuration.setServiceProviderMetadataPath(spMetadataPath);
    saml2Configuration.init();
    val saml2Client = new SAML2Client(saml2Configuration);
    saml2Client.setCallbackUrl("http://callback.example.org");
    saml2Client.init();
    saml2MessageContext = new SAML2MessageContext();
    saml2MessageContext.setSaml2Configuration(saml2Configuration);
    saml2MessageContext.setWebContext(new JEEContext(new MockHttpServletRequest(), new MockHttpServletResponse()));
    val peer = saml2MessageContext.getMessageContext().getSubcontext(SAMLPeerEntityContext.class, true);
    assertNotNull(peer);
    peer.setEntityId("https://cas.example.org/idp");
    val md = peer.getSubcontext(SAMLMetadataContext.class, true);
    assertNotNull(md);
    val idpResolver = SamlIdPUtils.getRoleDescriptorResolver(casSamlIdPMetadataResolver, true);
    md.setRoleDescriptor(idpResolver.resolveSingle(new CriteriaSet(new EntityIdCriterion(Objects.requireNonNull(peer.getEntityId())), new EntityRoleCriterion(IDPSSODescriptor.DEFAULT_ELEMENT_NAME))));
    val self = saml2MessageContext.getMessageContext().getSubcontext(SAMLSelfEntityContext.class, true);
    assertNotNull(self);
    self.setEntityId(saml2Configuration.getServiceProviderEntityId());
    val sp = self.getSubcontext(SAMLMetadataContext.class, true);
    assertNotNull(sp);
    val spRes = new InMemoryResourceMetadataResolver(new File(spMetadataPath), openSamlConfigBean);
    spRes.setId(getClass().getSimpleName());
    spRes.initialize();
    val spResolver = SamlIdPUtils.getRoleDescriptorResolver(spRes, true);
    sp.setRoleDescriptor(spResolver.resolveSingle(new CriteriaSet(new EntityIdCriterion(Objects.requireNonNull(self.getEntityId())), new EntityRoleCriterion(SPSSODescriptor.DEFAULT_ELEMENT_NAME))));
}
Also used : lombok.val(lombok.val) SAML2MessageContext(org.pac4j.saml.context.SAML2MessageContext) SAML2Configuration(org.pac4j.saml.config.SAML2Configuration) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) JEEContext(org.pac4j.core.context.JEEContext) CriteriaSet(net.shibboleth.utilities.java.support.resolver.CriteriaSet) EntityIdCriterion(org.opensaml.core.criterion.EntityIdCriterion) EntityRoleCriterion(org.opensaml.saml.criterion.EntityRoleCriterion) SAML2Client(org.pac4j.saml.client.SAML2Client) File(java.io.File) InMemoryResourceMetadataResolver(org.apereo.cas.support.saml.InMemoryResourceMetadataResolver) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 34 with JEEContext

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

the class EndpointLdapAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    try {
        val username = authentication.getPrincipal().toString();
        val credentials = authentication.getCredentials();
        val password = Optional.ofNullable(credentials).map(Object::toString).orElse(null);
        if (StringUtils.isBlank(password)) {
            throw new IllegalArgumentException("Password cannot be blank");
        }
        LOGGER.debug("Preparing LDAP authentication request for user [{}]", username);
        val request = new AuthenticationRequest(username, new Credential(password), ReturnAttributes.ALL.value());
        LOGGER.debug("Executing LDAP authentication request for user [{}]", username);
        val response = this.authenticator.authenticate(request);
        LOGGER.debug("LDAP response: [{}]", response);
        if (response.isSuccess()) {
            val roles = securityProperties.getUser().getRoles();
            if (roles.isEmpty()) {
                LOGGER.info("No user security roles are defined to enable authorization. User [{}] is considered authorized", username);
                return generateAuthenticationToken(authentication, new ArrayList<>(0));
            }
            val entry = response.getLdapEntry();
            val profile = new CommonProfile();
            profile.setId(username);
            entry.getAttributes().forEach(a -> profile.addAttribute(a.getName(), a.getStringValues()));
            LOGGER.debug("Collected user profile [{}]", profile);
            val context = new JEEContext(HttpRequestUtils.getHttpServletRequestFromRequestAttributes(), HttpRequestUtils.getHttpServletResponseFromRequestAttributes());
            val authZGen = buildAuthorizationGenerator();
            authZGen.generate(context, JEESessionStore.INSTANCE, profile);
            LOGGER.debug("Assembled user profile with roles after generating authorization claims [{}]", profile);
            val authorities = profile.getRoles().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toCollection(ArrayList::new));
            LOGGER.debug("List of authorities remapped from profile roles are [{}]", authorities);
            val authorizer = new RequireAnyRoleAuthorizer(roles);
            LOGGER.debug("Executing authorization for expected admin roles [{}]", authorizer.getElements());
            if (authorizer.isAllAuthorized(context, JEESessionStore.INSTANCE, CollectionUtils.wrap(profile))) {
                return generateAuthenticationToken(authentication, authorities);
            }
            LOGGER.warn("User [{}] is not authorized to access the requested resource allowed to roles [{}]", username, authorizer.getElements());
        } else {
            LOGGER.warn("LDAP authentication response produced no results for [{}]", username);
        }
    } catch (final Exception e) {
        LoggingUtils.error(LOGGER, e);
        throw new InsufficientAuthenticationException("Unexpected LDAP error", e);
    }
    throw new BadCredentialsException("Could not authenticate provided credentials");
}
Also used : lombok.val(lombok.val) Credential(org.ldaptive.Credential) CommonProfile(org.pac4j.core.profile.CommonProfile) JEEContext(org.pac4j.core.context.JEEContext) AuthenticationRequest(org.ldaptive.auth.AuthenticationRequest) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) RequireAnyRoleAuthorizer(org.pac4j.core.authorization.authorizer.RequireAnyRoleAuthorizer) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationException(org.springframework.security.core.AuthenticationException) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException)

Example 35 with JEEContext

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

the class SessionStoreTicketGrantingTicketAction method doExecute.

@Override
protected Event doExecute(final RequestContext requestContext) {
    val request = WebUtils.getHttpServletRequestFromExternalWebflowContext(requestContext);
    val response = WebUtils.getHttpServletResponseFromExternalWebflowContext(requestContext);
    val ticketGrantingTicketId = WebUtils.getTicketGrantingTicketId(requestContext);
    val webContext = new JEEContext(request, response);
    sessionStore.set(webContext, WebUtils.PARAMETER_TICKET_GRANTING_TICKET_ID, ticketGrantingTicketId);
    return null;
}
Also used : lombok.val(lombok.val) JEEContext(org.pac4j.core.context.JEEContext)

Aggregations

JEEContext (org.pac4j.core.context.JEEContext)224 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)28 UsernamePasswordCredentials (org.pac4j.core.credentials.UsernamePasswordCredentials)24 CommonProfile (org.pac4j.core.profile.CommonProfile)22 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)16 HashMap (java.util.HashMap)15 HttpServletRequest (javax.servlet.http.HttpServletRequest)14 HttpServletResponse (javax.servlet.http.HttpServletResponse)14 RedirectView (org.springframework.web.servlet.view.RedirectView)14 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