Search in sources :

Example 6 with OidcProfile

use of org.pac4j.oidc.profile.OidcProfile 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 7 with OidcProfile

use of org.pac4j.oidc.profile.OidcProfile in project pac4j by pac4j.

the class RunMitreIdOrg method verifyProfile.

@Override
protected void verifyProfile(final CommonProfile userProfile) {
    final OidcProfile profile = (OidcProfile) userProfile;
    assertEquals("90342.ASDFJWFA", profile.getId());
    assertEquals(OidcProfile.class.getName() + CommonProfile.SEPARATOR + "90342.ASDFJWFA", profile.getTypedId());
    assertNotNull(profile.getAccessToken());
    assertNotNull(profile.getIdToken());
    assertTrue(ProfileHelper.isTypedIdOf(profile.getTypedId(), OidcProfile.class));
    assertNotNull(profile.getIdTokenString());
    assertCommonProfile(profile, "admin@example.com", null, null, "Demo Admin", "admin", Gender.UNSPECIFIED, null, null, null, null);
    assertTrue((Boolean) profile.getAttribute("email_verified"));
    assertEquals("https://mitreid.org/", profile.getIssuer());
    assertEquals("acdf79d7-0129-4ba3-bc61-a52486cf82ff", profile.getAudience().get(0));
    assertNotNull(profile.getAuthTime());
    assertNotNull(profile.getExpirationDate());
    assertNotNull(profile.getIssuedAt());
    assertNotNull(profile.getAttribute("jti"));
    assertEquals(13, profile.getAttributes().size());
}
Also used : OidcProfile(org.pac4j.oidc.profile.OidcProfile)

Example 8 with OidcProfile

use of org.pac4j.oidc.profile.OidcProfile in project ddf by codice.

the class CustomOidcProfileCreator method create.

@Override
public Optional<UserProfile> create(OidcCredentials credentials, WebContext context) {
    init();
    final OidcProfile profile = (OidcProfile) getProfileDefinition().newProfile();
    final AccessToken accessToken = credentials.getAccessToken();
    if (accessToken != null && !accessToken.getValue().isEmpty()) {
        profile.setAccessToken(accessToken);
    }
    final RefreshToken refreshToken = credentials.getRefreshToken();
    if (refreshToken != null && !refreshToken.getValue().isEmpty()) {
        profile.setRefreshToken(refreshToken);
        LOGGER.debug("Found refresh token");
    }
    final JWT idToken = credentials.getIdToken();
    profile.setIdTokenString(idToken.getParsedString());
    try {
        JWTClaimsSet claimsSet = idToken.getJWTClaimsSet();
        assertNotNull("claimsSet", claimsSet);
        profile.setId(ProfileHelper.sanitizeIdentifier(profile, claimsSet.getSubject()));
        for (final Map.Entry<String, Object> entry : claimsSet.getClaims().entrySet()) {
            if (!JwtClaims.SUBJECT.equals(entry.getKey()) && profile.getAttribute(entry.getKey()) == null) {
                getProfileDefinition().convertAndAdd(profile, PROFILE_ATTRIBUTE, entry.getKey(), entry.getValue());
            }
        }
        profile.setTokenExpirationAdvance(configuration.getTokenExpirationAdvance());
        return Optional.of(profile);
    } catch (final java.text.ParseException e) {
        throw new AuthenticationException(e);
    }
}
Also used : RefreshToken(com.nimbusds.oauth2.sdk.token.RefreshToken) AuthenticationException(org.apache.shiro.authc.AuthenticationException) AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) JWT(com.nimbusds.jwt.JWT) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) OidcProfile(org.pac4j.oidc.profile.OidcProfile) WebContext(org.pac4j.core.context.WebContext) Map(java.util.Map)

Example 9 with OidcProfile

use of org.pac4j.oidc.profile.OidcProfile in project cas by apereo.

the class DelegatedClientJacksonModuleTests method verifyOperation.

@Test
@SuppressWarnings("JavaUtilDate")
public void verifyOperation() throws Exception {
    val mapper = SERIALIZER.getObjectMapper();
    assertTrue(mapper.getRegisteredModuleIds().contains(DelegatedClientJacksonModule.class.getName()));
    val jwt = new PlainJWT(new JWTClaimsSet.Builder().audience("audience").subject("subject").expirationTime(new Date()).issueTime(new Date()).claim("first_name", "name").build());
    val oidcProfile = new OidcProfile();
    oidcProfile.setId("id");
    oidcProfile.setIdTokenString(jwt.serialize());
    val ticket = new TransientSessionTicketImpl(UUID.randomUUID().toString(), NeverExpiresExpirationPolicy.INSTANCE, RegisteredServiceTestUtils.getService(), Map.of("profiles", oidcProfile));
    val content = mapper.writeValueAsString(ticket);
    assertNotNull(mapper.readValue(content, TransientSessionTicket.class));
}
Also used : lombok.val(lombok.val) TransientSessionTicket(org.apereo.cas.ticket.TransientSessionTicket) PlainJWT(com.nimbusds.jwt.PlainJWT) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) OidcProfile(org.pac4j.oidc.profile.OidcProfile) TransientSessionTicketImpl(org.apereo.cas.ticket.TransientSessionTicketImpl) Date(java.util.Date) Test(org.junit.jupiter.api.Test)

Example 10 with OidcProfile

use of org.pac4j.oidc.profile.OidcProfile 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)

Aggregations

OidcProfile (org.pac4j.oidc.profile.OidcProfile)10 WebContext (org.pac4j.core.context.WebContext)3 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)2 SecurityAssertion (ddf.security.assertion.SecurityAssertion)2 PrincipalHolder (ddf.security.common.PrincipalHolder)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 HttpSession (javax.servlet.http.HttpSession)2 AuthenticationException (org.apache.shiro.authc.AuthenticationException)2 SimplePrincipalCollection (org.apache.shiro.subject.SimplePrincipalCollection)2 OidcLogoutActionBuilder (org.pac4j.oidc.logout.OidcLogoutActionBuilder)2 JWT (com.nimbusds.jwt.JWT)1 PlainJWT (com.nimbusds.jwt.PlainJWT)1 AccessToken (com.nimbusds.oauth2.sdk.token.AccessToken)1 RefreshToken (com.nimbusds.oauth2.sdk.token.RefreshToken)1 OIDCProviderMetadata (com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata)1 ActionImpl (ddf.action.impl.ActionImpl)1 Subject (ddf.security.Subject)1 SubjectUtils (ddf.security.service.impl.SubjectUtils)1 MalformedURLException (java.net.MalformedURLException)1