Search in sources :

Example 46 with WebContext

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

the class OidcTokenValidatorTest method testValidateIdTokensExpiredToken.

@Test(expected = OidcValidationException.class)
public void testValidateIdTokensExpiredToken() throws Exception {
    WebContext context = getWebContext();
    String stringJwt = getIdTokenBuilder().withClaim("nonce", "myNonce").withExpiresAt(new Date(Instant.now().minus(Duration.ofDays(3)).toEpochMilli())).sign(invalidAlgorithm);
    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) Date(java.util.Date) Test(org.junit.Test)

Example 47 with WebContext

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

the class OidcTokenValidatorTest method testValidateIdTokensInvalidSignature.

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

Example 48 with WebContext

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

the class OidcTokenValidatorTest 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 49 with WebContext

use of org.pac4j.core.context.WebContext 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 50 with WebContext

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

the class OidcRealmTest method setup.

@Before
public void setup() throws Exception {
    realm = new OidcRealm();
    // Generate the RSA key pair
    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
    gen.initialize(2048);
    KeyPair keyPair = gen.generateKeyPair();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    validAlgorithm = Algorithm.RSA256(publicKey, privateKey);
    invalidAlgorithm = Algorithm.HMAC256("WRONG");
    JWK sigJwk = new RSAKey.Builder(publicKey).privateKey(privateKey).keyUse(KeyUse.SIGNATURE).keyID(UUID.randomUUID().toString()).build();
    String jwk = "{\"keys\": [" + sigJwk.toPublicJWK().toJSONString() + "] }";
    OIDCProviderMetadata oidcProviderMetadata = mock(OIDCProviderMetadata.class);
    when(oidcProviderMetadata.getIDTokenJWSAlgs()).thenReturn(ImmutableList.of(JWSAlgorithm.RS256));
    when(oidcProviderMetadata.getIssuer()).thenReturn(new Issuer("http://localhost:8080/auth/realms/master"));
    when(oidcProviderMetadata.getJWKSetURI()).thenReturn(new URI("http://localhost:8080/auth/realms/master/protocol/openid-connect/certs"));
    ResourceRetriever resourceRetriever = mock(ResourceRetriever.class);
    Resource resource = new Resource(jwk, APPLICATION_JSON);
    when(resourceRetriever.retrieveResource(any())).thenReturn(resource);
    OidcConfiguration configuration = mock(OidcConfiguration.class);
    when(configuration.getClientId()).thenReturn("ddf-client");
    when(configuration.getSecret()).thenReturn("secret");
    when(configuration.isUseNonce()).thenReturn(true);
    when(configuration.getResponseType()).thenReturn("code");
    when(configuration.findProviderMetadata()).thenReturn(oidcProviderMetadata);
    when(configuration.findResourceRetriever()).thenReturn(resourceRetriever);
    OidcHandlerConfiguration handlerConfiguration = mock(OidcHandlerConfiguration.class);
    when(handlerConfiguration.getOidcConfiguration()).thenReturn(configuration);
    when(handlerConfiguration.getOidcClient(any())).thenReturn(mock(OidcClient.class));
    realm.setOidcHandlerConfiguration(handlerConfiguration);
    realm.setUsernameAttributeList(Collections.singletonList("preferred_username"));
    JWT jwt = mock(JWT.class);
    AccessToken accessToken = new BearerAccessToken(getAccessTokenBuilder().sign(validAlgorithm));
    AuthorizationCode authorizationCode = new AuthorizationCode();
    WebContext webContext = getWebContext();
    oidcCredentials = mock(OidcCredentials.class);
    when(oidcCredentials.getIdToken()).thenReturn(jwt);
    when(oidcCredentials.getIdToken()).thenReturn(jwt);
    when(oidcCredentials.getAccessToken()).thenReturn(accessToken);
    when(oidcCredentials.getCode()).thenReturn(authorizationCode);
    authenticationToken = mock(OidcAuthenticationToken.class);
    when(authenticationToken.getCredentials()).thenReturn(oidcCredentials);
    when(authenticationToken.getContext()).thenReturn(webContext);
}
Also used : OidcHandlerConfiguration(org.codice.ddf.security.handler.api.OidcHandlerConfiguration) AuthorizationCode(com.nimbusds.oauth2.sdk.AuthorizationCode) KeyPair(java.security.KeyPair) WebContext(org.pac4j.core.context.WebContext) Issuer(com.nimbusds.oauth2.sdk.id.Issuer) ResourceRetriever(com.nimbusds.jose.util.ResourceRetriever) JWT(com.nimbusds.jwt.JWT) SignedJWT(com.nimbusds.jwt.SignedJWT) Resource(com.nimbusds.jose.util.Resource) OidcAuthenticationToken(org.codice.ddf.security.handler.OidcAuthenticationToken) KeyPairGenerator(java.security.KeyPairGenerator) URI(java.net.URI) OidcConfiguration(org.pac4j.oidc.config.OidcConfiguration) OidcCredentials(org.pac4j.oidc.credentials.OidcCredentials) RSAPublicKey(java.security.interfaces.RSAPublicKey) OidcClient(org.pac4j.oidc.client.OidcClient) AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) OIDCProviderMetadata(com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) JWK(com.nimbusds.jose.jwk.JWK) Before(org.junit.Before)

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