Search in sources :

Example 56 with WebContext

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

the class OidcRequestSupport method isValidIssuerForEndpoint.

/**
 * Is valid issuer for endpoint.
 *
 * @param webContext the web context
 * @param endpoint   the endpoint
 * @return true /false
 */
public boolean isValidIssuerForEndpoint(final WebContext webContext, final String endpoint) {
    val requestUrl = webContext.getRequestURL();
    val issuerFromRequestUrl = StringUtils.removeEnd(StringUtils.remove(requestUrl, '/' + endpoint), "/");
    val definedIssuer = oidcIssuerService.determineIssuer(Optional.empty());
    val definedIssuerWithSlash = StringUtils.appendIfMissing(definedIssuer, "/");
    val result = definedIssuer.equalsIgnoreCase(issuerFromRequestUrl) || issuerFromRequestUrl.startsWith(definedIssuerWithSlash);
    FunctionUtils.doIf(!result, o -> LOGGER.trace("Configured issuer [{}] defined does not match the request issuer [{}]", o, issuerFromRequestUrl)).accept(definedIssuer);
    return result;
}
Also used : lombok.val(lombok.val) Arrays(java.util.Arrays) SneakyThrows(lombok.SneakyThrows) ZonedDateTime(java.time.ZonedDateTime) RequiredArgsConstructor(lombok.RequiredArgsConstructor) TicketRegistrySupport(org.apereo.cas.ticket.registry.TicketRegistrySupport) StringUtils(org.apache.commons.lang3.StringUtils) WebContext(org.pac4j.core.context.WebContext) FunctionUtils(org.apereo.cas.util.function.FunctionUtils) CasCookieBuilder(org.apereo.cas.web.cookie.CasCookieBuilder) Authentication(org.apereo.cas.authentication.Authentication) CollectionUtils(org.apereo.cas.util.CollectionUtils) ZoneOffset(java.time.ZoneOffset) JEEContext(org.pac4j.core.context.JEEContext) CasProtocolConstants(org.apereo.cas.CasProtocolConstants) OAuth20Constants(org.apereo.cas.support.oauth.OAuth20Constants) URIBuilder(org.apache.http.client.utils.URIBuilder) OidcConstants(org.apereo.cas.oidc.OidcConstants) NonNull(lombok.NonNull) lombok.val(lombok.val) Set(java.util.Set) BasicUserProfile(org.pac4j.core.profile.BasicUserProfile) SessionStore(org.pac4j.core.context.session.SessionStore) ProfileManager(org.pac4j.core.profile.ProfileManager) Collectors(java.util.stream.Collectors) Slf4j(lombok.extern.slf4j.Slf4j) OidcIssuerService(org.apereo.cas.oidc.issuer.OidcIssuerService) NumberUtils(org.apache.commons.lang3.math.NumberUtils) Optional(java.util.Optional) UserProfile(org.pac4j.core.profile.UserProfile)

Example 57 with WebContext

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

the class OidcLogoutActionProvider method getAction.

/**
 * *
 *
 * @param <T> is a Map<String, Subject>
 * @param subjectMap containing the corresponding subject
 * @return OidcLogoutActionProvider containing the logout url
 */
@Override
public <T> Action getAction(T subjectMap) {
    if (!canHandle(subjectMap)) {
        return null;
    }
    String logoutUrlString = "";
    URL logoutUrl = null;
    try {
        HttpServletRequest request = (HttpServletRequest) ((Map) subjectMap).get("http_request");
        HttpServletResponse response = (HttpServletResponse) ((Map) subjectMap).get("http_response");
        JEESessionStore sessionStore = new JEESessionStore();
        JEEContext jeeContext = new JEEContext(request, response, sessionStore);
        HttpSession session = request.getSession(false);
        PrincipalHolder principalHolder = null;
        if (session != null) {
            principalHolder = (PrincipalHolder) session.getAttribute(SecurityConstants.SECURITY_TOKEN_KEY);
        }
        OidcProfile oidcProfile = null;
        if (principalHolder != null && principalHolder.getPrincipals() != null) {
            Collection<SecurityAssertion> securityAssertions = principalHolder.getPrincipals().byType(SecurityAssertion.class);
            for (SecurityAssertion securityAssertion : securityAssertions) {
                if (SecurityAssertionJwt.JWT_TOKEN_TYPE.equals(securityAssertion.getTokenType())) {
                    oidcProfile = (OidcProfile) securityAssertion.getToken();
                    break;
                }
            }
        }
        if (oidcProfile == null) {
            throw new IllegalStateException("Unable to determine OIDC profile for logout");
        }
        OidcLogoutActionBuilder logoutActionBuilder = handlerConfiguration.getOidcLogoutActionBuilder();
        logoutActionBuilder.setAjaxRequestResolver(new DefaultAjaxRequestResolver() {

            @Override
            public boolean isAjax(final WebContext context) {
                return false;
            }
        });
        URIBuilder urlBuilder = new URIBuilder(SystemBaseUrl.EXTERNAL.constructUrl("/oidc/logout", true));
        String prevUrl = getPreviousUrl(request);
        if (prevUrl != null) {
            urlBuilder.addParameter(PREV_URL, prevUrl);
        }
        RedirectionAction logoutAction = logoutActionBuilder.getLogoutAction(jeeContext, oidcProfile, urlBuilder.build().toString()).orElse(null);
        if (logoutAction instanceof WithLocationAction) {
            logoutUrlString = ((WithLocationAction) logoutAction).getLocation();
        }
        logoutUrl = new URL(logoutUrlString);
    } catch (MalformedURLException | URISyntaxException e) {
        LOGGER.info("Unable to resolve logout URL: {}", logoutUrlString);
    } catch (ClassCastException e) {
        LOGGER.debug("Unable to cast parameter to Map<String, Object>, {}", subjectMap, e);
    }
    return new ActionImpl(ID, TITLE, DESCRIPTION, logoutUrl);
}
Also used : RedirectionAction(org.pac4j.core.exception.http.RedirectionAction) MalformedURLException(java.net.MalformedURLException) WebContext(org.pac4j.core.context.WebContext) HttpSession(javax.servlet.http.HttpSession) JEEContext(org.pac4j.core.context.JEEContext) HttpServletResponse(javax.servlet.http.HttpServletResponse) JEESessionStore(org.pac4j.core.context.session.JEESessionStore) WithLocationAction(org.pac4j.core.exception.http.WithLocationAction) URISyntaxException(java.net.URISyntaxException) SecurityAssertion(ddf.security.assertion.SecurityAssertion) URL(java.net.URL) URIBuilder(org.apache.http.client.utils.URIBuilder) HttpServletRequest(javax.servlet.http.HttpServletRequest) DefaultAjaxRequestResolver(org.pac4j.core.http.ajax.DefaultAjaxRequestResolver) OidcLogoutActionBuilder(org.pac4j.oidc.logout.OidcLogoutActionBuilder) ActionImpl(ddf.action.impl.ActionImpl) OidcProfile(org.pac4j.oidc.profile.OidcProfile) PrincipalHolder(ddf.security.common.PrincipalHolder)

Example 58 with WebContext

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

the class KnoxSessionStoreTest method filterConfigParamsTest.

/**
 * Test exclusion of groups, roles and permissions
 * from pac4j profile object that is saved as a cookie.
 * @throws AliasServiceException
 */
@Test
public void filterConfigParamsTest() throws AliasServiceException {
    final AliasService aliasService = EasyMock.createNiceMock(AliasService.class);
    EasyMock.expect(aliasService.getPasswordFromAliasForCluster(CLUSTER_NAME, PAC4J_PASSWORD, true)).andReturn(PAC4J_PASSWORD.toCharArray()).anyTimes();
    EasyMock.expect(aliasService.getPasswordFromAliasForCluster(CLUSTER_NAME, PAC4J_PASSWORD)).andReturn(PAC4J_PASSWORD.toCharArray()).anyTimes();
    EasyMock.replay(aliasService);
    final DefaultCryptoService cryptoService = new DefaultCryptoService();
    cryptoService.setAliasService(aliasService);
    final Map<String, String> sessionStoreConfigs = new HashMap();
    final Capture<org.pac4j.core.context.Cookie> captureCookieValue = EasyMock.newCapture();
    final WebContext mockContext = EasyMock.createNiceMock(WebContext.class);
    EasyMock.expect(mockContext.getFullRequestURL()).andReturn("https://local.com/gateway/knoxsso/").anyTimes();
    mockContext.addResponseCookie(EasyMock.capture(captureCookieValue));
    EasyMock.replay(mockContext);
    final SAML2Profile samlProfile = new SAML2Profile();
    Set<String> groups = new HashSet<>(Arrays.asList("admin_2", "admin_1", "admin"));
    Set<String> roles = new HashSet<>(Arrays.asList("roles_2", "roles_1", "roles"));
    Set<String> permissions = new HashSet<>(Arrays.asList("permissions_2", "permissions_1", "permissions"));
    Map<String, Object> attributes = new HashMap<>();
    attributes.put("groups", groups);
    attributes.put("permissions", permissions);
    attributes.put("roles", roles);
    attributes.put("https://knox.apache.org/SAML/Attributes/groups", groups);
    attributes.put("https://knox.apache.org/SAML/Attributes/groups2", groups);
    samlProfile.addAttributes(attributes);
    /*
     * Test the default behavior where groups, roles and permissions are
     * excluded from the cookie.
     */
    /* Make sure groups are present */
    Assert.assertNotNull(samlProfile.getAttribute("groups"));
    Assert.assertNotNull(samlProfile.getAttribute("roles"));
    Assert.assertNotNull(samlProfile.getAttribute("permissions"));
    Assert.assertNotNull(samlProfile.getAttribute("https://knox.apache.org/SAML/Attributes/groups"));
    Assert.assertNotNull(samlProfile.getAttribute("https://knox.apache.org/SAML/Attributes/groups2"));
    sessionStoreConfigs.put(PAC4J_SESSION_STORE_EXCLUDE_GROUPS, PAC4J_SESSION_STORE_EXCLUDE_GROUPS_DEFAULT);
    sessionStoreConfigs.put(PAC4J_SESSION_STORE_EXCLUDE_ROLES, PAC4J_SESSION_STORE_EXCLUDE_ROLES_DEFAULT);
    sessionStoreConfigs.put(PAC4J_SESSION_STORE_EXCLUDE_PERMISSIONS, PAC4J_SESSION_STORE_EXCLUDE_PERMISSIONS_DEFAULT);
    sessionStoreConfigs.put(PAC4J_SESSION_STORE_EXCLUDE_CUSTOM_ATTRIBUTES, "https://knox.apache.org/SAML/Attributes/groups, https://knox.apache.org/SAML/Attributes/groups2");
    final Map<String, CommonProfile> profile = new HashMap<>();
    profile.put("SAML2Client", samlProfile);
    final KnoxSessionStore sessionStore = new KnoxSessionStore(cryptoService, CLUSTER_NAME, null, sessionStoreConfigs);
    sessionStore.set(mockContext, Pac4jConstants.USER_PROFILES, profile);
    /* Make sure groups are removed */
    Assert.assertNull(samlProfile.getAttribute("groups"));
    Assert.assertNull(samlProfile.getAttribute("roles"));
    Assert.assertNull(samlProfile.getAttribute("permissions"));
    Assert.assertNull(samlProfile.getAttribute("https://knox.apache.org/SAML/Attributes/groups"));
    Assert.assertNull(samlProfile.getAttribute("https://knox.apache.org/SAML/Attributes/groups2"));
    /*
     * Test the override behavior where groups, roles and permissions are
     * not-excluded from the cookie.
     */
    attributes.put("groups", groups);
    attributes.put("permissions", permissions);
    attributes.put("roles", roles);
    attributes.put("https://knox.apache.org/SAML/Attributes/groups", groups);
    attributes.put("https://knox.apache.org/SAML/Attributes/groups2", groups);
    samlProfile.addAttributes(attributes);
    /* Make sure groups are present */
    Assert.assertNotNull(samlProfile.getAttribute("groups"));
    Assert.assertNotNull(samlProfile.getAttribute("roles"));
    Assert.assertNotNull(samlProfile.getAttribute("permissions"));
    Assert.assertNotNull(samlProfile.getAttribute("https://knox.apache.org/SAML/Attributes/groups"));
    Assert.assertNotNull(samlProfile.getAttribute("https://knox.apache.org/SAML/Attributes/groups2"));
    sessionStoreConfigs.put(PAC4J_SESSION_STORE_EXCLUDE_GROUPS, "false");
    sessionStoreConfigs.put(PAC4J_SESSION_STORE_EXCLUDE_ROLES, "false");
    sessionStoreConfigs.put(PAC4J_SESSION_STORE_EXCLUDE_PERMISSIONS, "false");
    sessionStoreConfigs.put(PAC4J_SESSION_STORE_EXCLUDE_CUSTOM_ATTRIBUTES, "");
    profile.put("SAML2Client", samlProfile);
    sessionStore.set(mockContext, Pac4jConstants.USER_PROFILES, profile);
    /* Make sure attributes are not removed */
    Assert.assertNotNull(samlProfile.getAttribute("groups"));
    Assert.assertNotNull(samlProfile.getAttribute("roles"));
    Assert.assertNotNull(samlProfile.getAttribute("permissions"));
    Assert.assertNotNull(samlProfile.getAttribute("https://knox.apache.org/SAML/Attributes/groups"));
    Assert.assertNotNull(samlProfile.getAttribute("https://knox.apache.org/SAML/Attributes/groups2"));
}
Also used : AliasService(org.apache.knox.gateway.services.security.AliasService) WebContext(org.pac4j.core.context.WebContext) HashMap(java.util.HashMap) CommonProfile(org.pac4j.core.profile.CommonProfile) SAML2Profile(org.pac4j.saml.profile.SAML2Profile) DefaultCryptoService(org.apache.knox.gateway.services.security.impl.DefaultCryptoService) HashSet(java.util.HashSet) Test(org.junit.Test)

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