Search in sources :

Example 21 with WebContext

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

the class DefaultDelegatedClientAuthenticationWebflowManager method storeDelegatedClientAuthenticationRequest.

/**
 * Store delegated client authentication request.
 *
 * @param webContext the web context
 * @return the transient session ticket
 * @throws Exception the exception
 */
protected TransientSessionTicket storeDelegatedClientAuthenticationRequest(final JEEContext webContext) throws Exception {
    val properties = buildTicketProperties(webContext);
    val originalService = configContext.getArgumentExtractor().extractService(webContext.getNativeRequest());
    val service = configContext.getAuthenticationRequestServiceSelectionStrategies().resolveService(originalService);
    properties.put(CasProtocolConstants.PARAMETER_SERVICE, originalService);
    properties.put(CasProtocolConstants.PARAMETER_TARGET_SERVICE, service);
    val registeredService = configContext.getServicesManager().findServiceBy(service);
    webContext.getRequestParameter(RedirectionActionBuilder.ATTRIBUTE_FORCE_AUTHN).or(() -> Optional.of(Boolean.toString(RegisteredServiceProperties.DELEGATED_AUTHN_FORCE_AUTHN.isAssignedTo(registeredService)))).filter(value -> StringUtils.equalsIgnoreCase(value, "true")).ifPresent(attr -> properties.put(RedirectionActionBuilder.ATTRIBUTE_FORCE_AUTHN, true));
    webContext.getRequestParameter(RedirectionActionBuilder.ATTRIBUTE_PASSIVE).or(() -> Optional.of(Boolean.toString(RegisteredServiceProperties.DELEGATED_AUTHN_PASSIVE_AUTHN.isAssignedTo(registeredService)))).filter(value -> StringUtils.equalsIgnoreCase(value, "true")).ifPresent(attr -> properties.put(RedirectionActionBuilder.ATTRIBUTE_PASSIVE, true));
    val transientFactory = (TransientSessionTicketFactory) configContext.getTicketFactory().get(TransientSessionTicket.class);
    val ticket = transientFactory.create(originalService, properties);
    LOGGER.debug("Storing delegated authentication request ticket [{}] for service [{}] with properties [{}]", ticket.getId(), ticket.getService(), ticket.getProperties());
    configContext.getCentralAuthenticationService().addTicket(ticket);
    webContext.setRequestAttribute(PARAMETER_CLIENT_ID, ticket.getId());
    if (properties.containsKey(RedirectionActionBuilder.ATTRIBUTE_FORCE_AUTHN)) {
        webContext.setRequestAttribute(RedirectionActionBuilder.ATTRIBUTE_FORCE_AUTHN, true);
    }
    if (properties.containsKey(RedirectionActionBuilder.ATTRIBUTE_PASSIVE)) {
        webContext.setRequestAttribute(RedirectionActionBuilder.ATTRIBUTE_PASSIVE, true);
    }
    return ticket;
}
Also used : lombok.val(lombok.val) CasClient(org.pac4j.cas.client.CasClient) Getter(lombok.Getter) RegisteredServiceProperties(org.apereo.cas.services.RegisteredServiceProperty.RegisteredServiceProperties) RequiredArgsConstructor(lombok.RequiredArgsConstructor) SAML2Client(org.pac4j.saml.client.SAML2Client) HashMap(java.util.HashMap) DelegatedClientAuthenticationWebflowManager(org.apereo.cas.web.flow.DelegatedClientAuthenticationWebflowManager) StringUtils(org.apache.commons.lang3.StringUtils) RequestContext(org.springframework.webflow.execution.RequestContext) SAML2StateGenerator(org.pac4j.saml.state.SAML2StateGenerator) WebContext(org.pac4j.core.context.WebContext) TransientSessionTicketFactory(org.apereo.cas.ticket.TransientSessionTicketFactory) OidcClient(org.pac4j.oidc.client.OidcClient) Client(org.pac4j.core.client.Client) Map(java.util.Map) JEEContext(org.pac4j.core.context.JEEContext) RedirectionActionBuilder(org.pac4j.core.redirect.RedirectionActionBuilder) CasProtocolConstants(org.apereo.cas.CasProtocolConstants) TransientSessionTicket(org.apereo.cas.ticket.TransientSessionTicket) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) lombok.val(lombok.val) Serializable(java.io.Serializable) SamlProtocolConstants(org.apereo.cas.support.saml.SamlProtocolConstants) Slf4j(lombok.extern.slf4j.Slf4j) OAuth10Client(org.pac4j.oauth.client.OAuth10Client) Service(org.apereo.cas.authentication.principal.Service) DelegatedClientAuthenticationConfigurationContext(org.apereo.cas.web.flow.DelegatedClientAuthenticationConfigurationContext) Optional(java.util.Optional) WebUtils(org.apereo.cas.web.support.WebUtils) OAuth20Client(org.pac4j.oauth.client.OAuth20Client) Transactional(org.springframework.transaction.annotation.Transactional) TransientSessionTicket(org.apereo.cas.ticket.TransientSessionTicket) TransientSessionTicketFactory(org.apereo.cas.ticket.TransientSessionTicketFactory)

Example 22 with WebContext

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

the class OidcRealmTest method getWebContext.

private WebContext getWebContext() {
    WebContext context = mock(WebContext.class);
    SessionStore sessionStore = mock(SessionStore.class);
    when(sessionStore.get(context, NONCE_SESSION_ATTRIBUTE)).thenReturn(Optional.of("myNonce"));
    when(context.getSessionStore()).thenReturn(sessionStore);
    return context;
}
Also used : SessionStore(org.pac4j.core.context.session.SessionStore) WebContext(org.pac4j.core.context.WebContext)

Example 23 with WebContext

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

the class OidcRealm method doGetAuthenticationInfo.

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    // token is guaranteed to be of type OidcAuthenticationToken by the supports() method
    OidcAuthenticationToken oidcAuthenticationToken = (OidcAuthenticationToken) authenticationToken;
    OidcCredentials credentials = (OidcCredentials) oidcAuthenticationToken.getCredentials();
    OidcConfiguration oidcConfiguration = oidcHandlerConfiguration.getOidcConfiguration();
    OIDCProviderMetadata oidcProviderMetadata = oidcConfiguration.findProviderMetadata();
    WebContext webContext = (WebContext) oidcAuthenticationToken.getContext();
    OidcClient<OidcConfiguration> oidcClient = oidcHandlerConfiguration.getOidcClient(webContext.getFullRequestURL());
    int connectTimeout = oidcHandlerConfiguration.getConnectTimeout();
    int readTimeout = oidcHandlerConfiguration.getReadTimeout();
    try {
        OidcCredentialsResolver oidcCredentialsResolver = new OidcCredentialsResolver(oidcConfiguration, oidcClient, oidcProviderMetadata, connectTimeout, readTimeout);
        oidcCredentialsResolver.resolveIdToken(credentials, webContext);
    } catch (TechnicalException e) {
        throw new AuthenticationException(e);
    }
    // problem getting id token, invalidate credentials
    if (credentials.getIdToken() == null) {
        webContext.getSessionStore().destroySession(webContext);
        String msg = String.format("Could not fetch id token with Oidc credentials (%s). " + "This may be due to the credentials expiring. " + "Invalidating session in order to acquire valid credentials.", credentials);
        LOGGER.warn(msg);
        throw new AuthenticationException(msg);
    }
    OidcProfileCreator oidcProfileCreator = new CustomOidcProfileCreator(oidcConfiguration, oidcClient);
    Optional<UserProfile> userProfile = oidcProfileCreator.create(credentials, webContext);
    SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo();
    simpleAuthenticationInfo.setCredentials(credentials);
    if (userProfile.isPresent()) {
        OidcProfile oidcProfile = (OidcProfile) userProfile.get();
        simpleAuthenticationInfo.setPrincipals(createPrincipalCollectionFromCredentials(oidcProfile));
    } else {
        simpleAuthenticationInfo.setPrincipals(new SimplePrincipalCollection());
    }
    return simpleAuthenticationInfo;
}
Also used : WebContext(org.pac4j.core.context.WebContext) TechnicalException(org.pac4j.core.exception.TechnicalException) UserProfile(org.pac4j.core.profile.UserProfile) SimpleAuthenticationInfo(org.apache.shiro.authc.SimpleAuthenticationInfo) AuthenticationException(org.apache.shiro.authc.AuthenticationException) OidcAuthenticationToken(org.codice.ddf.security.handler.OidcAuthenticationToken) SimplePrincipalCollection(org.apache.shiro.subject.SimplePrincipalCollection) OidcCredentialsResolver(org.codice.ddf.security.oidc.resolver.OidcCredentialsResolver) OidcConfiguration(org.pac4j.oidc.config.OidcConfiguration) OidcCredentials(org.pac4j.oidc.credentials.OidcCredentials) OidcProfileCreator(org.pac4j.oidc.profile.creator.OidcProfileCreator) OidcProfile(org.pac4j.oidc.profile.OidcProfile) OIDCProviderMetadata(com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata)

Example 24 with WebContext

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

the class OidcRealm method supports.

/**
 * Determine if the supplied token is supported by this realm.
 */
@Override
public boolean supports(AuthenticationToken token) {
    if (!(token instanceof OidcAuthenticationToken)) {
        LOGGER.debug("The supplied authentication token is not an instance of SessionToken or OidcAuthenticationToken. Sending back not supported.");
        return false;
    }
    OidcAuthenticationToken oidcToken = (OidcAuthenticationToken) token;
    OidcCredentials credentials = (OidcCredentials) oidcToken.getCredentials();
    if (credentials == null || (credentials.getCode() == null && credentials.getAccessToken() == null && credentials.getIdToken() == null)) {
        LOGGER.debug("The supplied authentication token has null/empty credentials. Sending back no supported.");
        return false;
    }
    WebContext webContext = (WebContext) oidcToken.getContext();
    if (webContext == null) {
        LOGGER.debug("The supplied authentication token has null web context. Sending back not supported.");
        return false;
    }
    LOGGER.debug("Token {} is supported by {}.", token.getClass(), OidcRealm.class.getName());
    return true;
}
Also used : OidcCredentials(org.pac4j.oidc.credentials.OidcCredentials) WebContext(org.pac4j.core.context.WebContext) OidcAuthenticationToken(org.codice.ddf.security.handler.OidcAuthenticationToken)

Example 25 with WebContext

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

the class OidcTokenValidatorTest method testValidateIdTokens.

@Test
public void testValidateIdTokens() throws Exception {
    WebContext context = getWebContext();
    String stringJwt = getIdTokenBuilder().withClaim("nonce", "myNonce").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)

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