Search in sources :

Example 1 with AuthenticationChannelRequest

use of org.keycloak.protocol.oidc.grants.ciba.channel.AuthenticationChannelRequest in project keycloak by keycloak.

the class CIBATest method testBackchannelAuthenticationFlowWithInvalidSignedAuthenticationRequest.

@Test
public void testBackchannelAuthenticationFlowWithInvalidSignedAuthenticationRequest() throws Exception {
    ClientResource clientResource = null;
    ClientRepresentation clientRep = null;
    try {
        boolean useRequestUri = false;
        String sigAlg = Algorithm.PS256;
        final String username = "nutzername-rot";
        String bindingMessage = "Flughafen-Frankfurt-am-Main";
        // prepare CIBA settings
        clientResource = ApiUtil.findClientByClientId(adminClient.realm(TEST_REALM_NAME), TEST_CLIENT_NAME);
        clientRep = clientResource.toRepresentation();
        prepareCIBASettings(clientResource, clientRep);
        // register profiles
        String json = (new ClientProfilesBuilder()).addProfile((new ClientProfileBuilder()).createProfile(PROFILE_NAME, "Le Premier Profil").addExecutor(SecureCibaSignedAuthenticationRequestExecutorFactory.PROVIDER_ID, null).toRepresentation()).toString();
        updateProfiles(json);
        // register policies
        json = (new ClientPoliciesBuilder()).addPolicy((new ClientPolicyBuilder()).createPolicy(POLICY_NAME, "La Premiere Politique", Boolean.TRUE).addCondition(AnyClientConditionFactory.PROVIDER_ID, createAnyClientConditionConfig()).addProfile(PROFILE_NAME).toRepresentation()).toString();
        updatePolicies(json);
        AuthorizationEndpointRequestObject requestObject = createPartialAuthorizationEndpointRequestObject(username, bindingMessage);
        requestObject.nbf(requestObject.getIat());
        registerSharedAuthenticationRequest(requestObject, TEST_CLIENT_NAME, sigAlg, useRequestUri);
        // user Backchannel Authentication Request
        AuthenticationRequestAcknowledgement response = oauth.doBackchannelAuthenticationRequest(TEST_CLIENT_NAME, TEST_CLIENT_PASSWORD, username, bindingMessage, null, null, null);
        assertThat(response.getStatusCode(), is(equalTo(400)));
        assertThat(response.getError(), is(OAuthErrorException.INVALID_REQUEST));
        assertThat(response.getErrorDescription(), is("Missing parameter in the signed authentication request: exp"));
        useRequestUri = true;
        bindingMessage = "Flughafen-Wien-Schwechat";
        requestObject = createPartialAuthorizationEndpointRequestObject(username, bindingMessage);
        requestObject.exp(requestObject.getIat() + Long.valueOf(300));
        registerSharedAuthenticationRequest(requestObject, TEST_CLIENT_NAME, sigAlg, useRequestUri);
        // user Backchannel Authentication Request
        response = oauth.doBackchannelAuthenticationRequest(TEST_CLIENT_NAME, TEST_CLIENT_PASSWORD, username, bindingMessage, null, null, null);
        assertThat(response.getStatusCode(), is(equalTo(400)));
        assertThat(response.getError(), is(OAuthErrorException.INVALID_REQUEST));
        assertThat(response.getErrorDescription(), is("Missing parameter in the signed authentication request: nbf"));
        useRequestUri = false;
        bindingMessage = "Stuttgart-Hauptbahnhof";
        requestObject = createPartialAuthorizationEndpointRequestObject(username, bindingMessage);
        requestObject.exp(requestObject.getIat() + SecureCibaSignedAuthenticationRequestExecutor.DEFAULT_AVAILABLE_PERIOD + 10);
        requestObject.nbf(requestObject.getIat());
        registerSharedAuthenticationRequest(requestObject, TEST_CLIENT_NAME, sigAlg, useRequestUri);
        // user Backchannel Authentication Request
        response = oauth.doBackchannelAuthenticationRequest(TEST_CLIENT_NAME, TEST_CLIENT_PASSWORD, username, bindingMessage, null, null, null);
        assertThat(response.getStatusCode(), is(equalTo(400)));
        assertThat(response.getError(), is(OAuthErrorException.INVALID_REQUEST));
        assertThat(response.getErrorDescription(), is("signed authentication request's available period is long"));
        useRequestUri = true;
        bindingMessage = "Flughafen-Wien-Schwechat";
        requestObject = createPartialAuthorizationEndpointRequestObject(username, bindingMessage);
        requestObject.exp(requestObject.getIat() + Long.valueOf(300));
        requestObject.nbf(requestObject.getIat());
        requestObject.audience(null);
        registerSharedAuthenticationRequest(requestObject, TEST_CLIENT_NAME, sigAlg, useRequestUri);
        // user Backchannel Authentication Request
        response = oauth.doBackchannelAuthenticationRequest(TEST_CLIENT_NAME, TEST_CLIENT_PASSWORD, username, bindingMessage, null, null, null);
        assertThat(response.getStatusCode(), is(equalTo(400)));
        assertThat(response.getError(), is(OAuthErrorException.INVALID_REQUEST));
        assertThat(response.getErrorDescription(), is("Missing parameter in the 'request' object: aud"));
        useRequestUri = false;
        bindingMessage = "Stuttgart-Hauptbahnhof";
        requestObject = createPartialAuthorizationEndpointRequestObject(username, bindingMessage);
        requestObject.exp(requestObject.getIat() + Long.valueOf(300));
        requestObject.nbf(requestObject.getIat());
        requestObject.audience("https://example.com");
        registerSharedAuthenticationRequest(requestObject, TEST_CLIENT_NAME, sigAlg, useRequestUri);
        // user Backchannel Authentication Request
        response = oauth.doBackchannelAuthenticationRequest(TEST_CLIENT_NAME, TEST_CLIENT_PASSWORD, username, bindingMessage, null, null, null);
        assertThat(response.getStatusCode(), is(equalTo(400)));
        assertThat(response.getError(), is(OAuthErrorException.INVALID_REQUEST));
        assertThat(response.getErrorDescription(), is("Invalid parameter in the 'request' object: aud"));
        useRequestUri = true;
        bindingMessage = "Flughafen-Wien-Schwechat";
        requestObject = createPartialAuthorizationEndpointRequestObject(username, bindingMessage);
        requestObject.exp(requestObject.getIat() + Long.valueOf(300));
        requestObject.nbf(requestObject.getIat());
        requestObject.audience(Urls.realmIssuer(new URI(suiteContext.getAuthServerInfo().getContextRoot().toString() + "/auth"), REALM_NAME), "https://example.com");
        registerSharedAuthenticationRequest(requestObject, TEST_CLIENT_NAME, sigAlg, useRequestUri);
        // user Backchannel Authentication Request
        response = oauth.doBackchannelAuthenticationRequest(TEST_CLIENT_NAME, TEST_CLIENT_PASSWORD, username, bindingMessage, null, null, null);
        assertThat(response.getStatusCode(), is(equalTo(400)));
        assertThat(response.getError(), is(OAuthErrorException.INVALID_REQUEST));
        assertThat(response.getErrorDescription(), is("Missing parameter in the 'request' object: iss"));
        useRequestUri = false;
        bindingMessage = "Stuttgart-Hauptbahnhof";
        requestObject = createPartialAuthorizationEndpointRequestObject(username, bindingMessage);
        requestObject.exp(requestObject.getIat() + Long.valueOf(300));
        requestObject.nbf(requestObject.getIat());
        requestObject.audience(Urls.realmIssuer(new URI(suiteContext.getAuthServerInfo().getContextRoot().toString() + "/auth"), REALM_NAME), "https://example.com");
        requestObject.issuer(TEST_CLIENT_NAME + TEST_CLIENT_NAME);
        registerSharedAuthenticationRequest(requestObject, TEST_CLIENT_NAME, sigAlg, useRequestUri);
        // user Backchannel Authentication Request
        response = oauth.doBackchannelAuthenticationRequest(TEST_CLIENT_NAME, TEST_CLIENT_PASSWORD, username, bindingMessage, null, null, null);
        assertThat(response.getStatusCode(), is(equalTo(400)));
        assertThat(response.getError(), is(OAuthErrorException.INVALID_REQUEST));
        assertThat(response.getErrorDescription(), is("Invalid parameter in the 'request' object: iss"));
        useRequestUri = true;
        bindingMessage = "Flughafen-Wien-Schwechat";
        requestObject = createPartialAuthorizationEndpointRequestObject(username, bindingMessage);
        requestObject.exp(requestObject.getIat() + Long.valueOf(300));
        requestObject.nbf(requestObject.getIat());
        requestObject.audience(Urls.realmIssuer(new URI(suiteContext.getAuthServerInfo().getContextRoot().toString() + "/auth"), REALM_NAME), "https://example.com");
        requestObject.issuer(TEST_CLIENT_NAME);
        requestObject.iat(null);
        requestObject.id(null);
        registerSharedAuthenticationRequest(requestObject, TEST_CLIENT_NAME, sigAlg, useRequestUri);
        // user Backchannel Authentication Request
        response = oauth.doBackchannelAuthenticationRequest(TEST_CLIENT_NAME, TEST_CLIENT_PASSWORD, username, bindingMessage, null, null, null);
        assertThat(response.getStatusCode(), is(equalTo(400)));
        assertThat(response.getError(), is(OAuthErrorException.INVALID_REQUEST));
        assertThat(response.getErrorDescription(), is("Missing parameter in the signed authentication request: iat"));
        useRequestUri = false;
        bindingMessage = "Stuttgart-Hauptbahnhof";
        requestObject = createPartialAuthorizationEndpointRequestObject(username, bindingMessage);
        requestObject.exp(requestObject.getIat() + Long.valueOf(300));
        requestObject.nbf(requestObject.getIat());
        requestObject.audience(Urls.realmIssuer(new URI(suiteContext.getAuthServerInfo().getContextRoot().toString() + "/auth"), REALM_NAME), "https://example.com");
        requestObject.issuer(TEST_CLIENT_NAME);
        requestObject.iat(Long.valueOf(Time.currentTime()));
        requestObject.id(null);
        registerSharedAuthenticationRequest(requestObject, TEST_CLIENT_NAME, sigAlg, useRequestUri);
        // user Backchannel Authentication Request
        response = oauth.doBackchannelAuthenticationRequest(TEST_CLIENT_NAME, TEST_CLIENT_PASSWORD, username, bindingMessage, null, null, null);
        assertThat(response.getStatusCode(), is(equalTo(400)));
        assertThat(response.getError(), is(OAuthErrorException.INVALID_REQUEST));
        assertThat(response.getErrorDescription(), is("Missing parameter in the signed authentication request: jti"));
        useRequestUri = true;
        bindingMessage = "Brno-hlavni-nadrazif";
        requestObject = createPartialAuthorizationEndpointRequestObject(username, bindingMessage);
        requestObject.exp(requestObject.getIat() + Long.valueOf(300));
        requestObject.nbf(requestObject.getIat());
        requestObject.audience(Urls.realmIssuer(new URI(suiteContext.getAuthServerInfo().getContextRoot().toString() + "/auth"), REALM_NAME), "https://example.com");
        requestObject.issuer(TEST_CLIENT_NAME);
        requestObject.id(org.keycloak.models.utils.KeycloakModelUtils.generateId());
        requestObject.iat(Long.valueOf(Time.currentTime()));
        registerSharedAuthenticationRequest(requestObject, TEST_CLIENT_NAME, sigAlg, useRequestUri);
        // user Backchannel Authentication Request
        response = doBackchannelAuthenticationRequest(TEST_CLIENT_NAME, TEST_CLIENT_PASSWORD, username, bindingMessage);
        // user Authentication Channel Request
        TestAuthenticationChannelRequest testRequest = doAuthenticationChannelRequest(bindingMessage);
        AuthenticationChannelRequest authenticationChannelReq = testRequest.getRequest();
        assertThat(authenticationChannelReq.getBindingMessage(), is(equalTo(bindingMessage)));
        assertThat(authenticationChannelReq.getScope(), is(containsString(OAuth2Constants.SCOPE_OPENID)));
        // user Authentication Channel completed
        doAuthenticationChannelCallback(testRequest);
        // user Token Request
        doBackchannelAuthenticationTokenRequest(username, response.getAuthReqId());
    } finally {
        revertCIBASettings(clientResource, clientRep);
    }
}
Also used : ClientProfilesBuilder(org.keycloak.testsuite.util.ClientPoliciesUtil.ClientProfilesBuilder) ClientPoliciesBuilder(org.keycloak.testsuite.util.ClientPoliciesUtil.ClientPoliciesBuilder) ClientPolicyBuilder(org.keycloak.testsuite.util.ClientPoliciesUtil.ClientPolicyBuilder) Matchers.containsString(org.hamcrest.Matchers.containsString) AuthenticationRequestAcknowledgement(org.keycloak.testsuite.util.OAuthClient.AuthenticationRequestAcknowledgement) URI(java.net.URI) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) ClientProfileBuilder(org.keycloak.testsuite.util.ClientPoliciesUtil.ClientProfileBuilder) AuthorizationEndpointRequestObject(org.keycloak.testsuite.rest.resource.TestingOIDCEndpointsApplicationResource.AuthorizationEndpointRequestObject) ClientResource(org.keycloak.admin.client.resource.ClientResource) AuthenticationChannelRequest(org.keycloak.protocol.oidc.grants.ciba.channel.AuthenticationChannelRequest) TestAuthenticationChannelRequest(org.keycloak.testsuite.rest.representation.TestAuthenticationChannelRequest) TestAuthenticationChannelRequest(org.keycloak.testsuite.rest.representation.TestAuthenticationChannelRequest) Test(org.junit.Test)

Example 2 with AuthenticationChannelRequest

use of org.keycloak.protocol.oidc.grants.ciba.channel.AuthenticationChannelRequest in project keycloak by keycloak.

the class FAPICIBATest method testFAPICIBALoginWithPrivateKeyJWT.

@Test
public void testFAPICIBALoginWithPrivateKeyJWT() throws Exception {
    setupPolicyFAPICIBAForAllClient();
    // Register client with private-key-jwt
    String clientUUID = createClientByAdmin(clientId, (ClientRepresentation clientRep) -> {
        clientRep.setClientAuthenticatorType(JWTClientAuthenticator.PROVIDER_ID);
        setClientAuthMethodNeutralSettings(clientRep);
    });
    ClientResource clientResource = adminClient.realm(REALM_NAME).clients().get(clientUUID);
    ClientRepresentation client = clientResource.toRepresentation();
    assertEquals(JWTClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType());
    // prepare valid signed authentication request
    AuthorizationEndpointRequestObject requestObject = createFAPIValidAuthorizationEndpointRequestObject(username, bindingMessage);
    String encodedRequestObject = registerSharedAuthenticationRequest(requestObject, clientId, Algorithm.PS256);
    // Get keys of client. Will be used for client authentication and signing of authentication request
    TestOIDCEndpointsApplicationResource oidcClientEndpointsResource = testingClient.testApp().oidcClientEndpoints();
    Map<String, String> generatedKeys = oidcClientEndpointsResource.getKeysAsBase64();
    KeyPair keyPair = getKeyPairFromGeneratedBase64(generatedKeys, Algorithm.PS256);
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();
    String signedJwt = createSignedRequestToken(clientId, privateKey, publicKey, org.keycloak.crypto.Algorithm.PS256);
    // user Backchannel Authentication Request
    AuthenticationRequestAcknowledgement response = doBackchannelAuthenticationRequestWithClientSignedJWT(signedJwt, encodedRequestObject, () -> MutualTLSUtils.newCloseableHttpClientWithDefaultKeyStoreAndTrustStore());
    assertThat(response.getStatusCode(), is(equalTo(200)));
    // user Authentication Channel Request
    TestAuthenticationChannelRequest testRequest = doAuthenticationChannelRequest(bindingMessage);
    AuthenticationChannelRequest authenticationChannelReq = testRequest.getRequest();
    assertThat(authenticationChannelReq.getBindingMessage(), is(equalTo(bindingMessage)));
    assertThat(authenticationChannelReq.getScope(), is(containsString(OAuth2Constants.SCOPE_OPENID)));
    // user Authentication Channel completed
    doAuthenticationChannelCallback(testRequest);
    String signedJwt2 = createSignedRequestToken(clientId, privateKey, publicKey, org.keycloak.crypto.Algorithm.PS256);
    // user Token Request
    OAuthClient.AccessTokenResponse tokenRes = doBackchannelAuthenticationTokenRequestWithClientSignedJWT(signedJwt2, response.getAuthReqId(), () -> MutualTLSUtils.newCloseableHttpClientWithDefaultKeyStoreAndTrustStore());
    verifyBackchannelAuthenticationTokenRequest(tokenRes, clientId, username);
    // Logout and remove consent of the user for next logins
    logoutUserAndRevokeConsent(clientId, username);
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) TestOIDCEndpointsApplicationResource(org.keycloak.testsuite.client.resources.TestOIDCEndpointsApplicationResource) OAuthClient(org.keycloak.testsuite.util.OAuthClient) PublicKey(java.security.PublicKey) Matchers.containsString(org.hamcrest.Matchers.containsString) AuthenticationRequestAcknowledgement(org.keycloak.testsuite.util.OAuthClient.AuthenticationRequestAcknowledgement) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) AuthorizationEndpointRequestObject(org.keycloak.testsuite.rest.resource.TestingOIDCEndpointsApplicationResource.AuthorizationEndpointRequestObject) ClientResource(org.keycloak.admin.client.resource.ClientResource) AuthenticationChannelRequest(org.keycloak.protocol.oidc.grants.ciba.channel.AuthenticationChannelRequest) TestAuthenticationChannelRequest(org.keycloak.testsuite.rest.representation.TestAuthenticationChannelRequest) TestAuthenticationChannelRequest(org.keycloak.testsuite.rest.representation.TestAuthenticationChannelRequest) Test(org.junit.Test)

Example 3 with AuthenticationChannelRequest

use of org.keycloak.protocol.oidc.grants.ciba.channel.AuthenticationChannelRequest in project keycloak by keycloak.

the class FAPICIBATest method testFAPICIBALoginWithMTLS.

@Test
public void testFAPICIBALoginWithMTLS() throws Exception {
    setupPolicyFAPICIBAForAllClient();
    // Register client with X509
    String clientUUID = createClientByAdmin("foo", (ClientRepresentation clientRep) -> {
        clientRep.setClientAuthenticatorType(X509ClientAuthenticator.PROVIDER_ID);
        OIDCAdvancedConfigWrapper clientConfig = OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep);
        clientConfig.setRequestUris(Collections.singletonList(TestApplicationResourceUrls.clientRequestUri()));
        clientConfig.setTlsClientAuthSubjectDn("EMAILADDRESS=contact@keycloak.org, CN=Keycloak Intermediate CA, OU=Keycloak, O=Red Hat, ST=MA, C=US");
        setClientAuthMethodNeutralSettings(clientRep);
    });
    ClientResource clientResource = adminClient.realm(REALM_NAME).clients().get(clientUUID);
    ClientRepresentation client = clientResource.toRepresentation();
    assertEquals(X509ClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType());
    // prepare valid signed authentication request
    AuthorizationEndpointRequestObject requestObject = createFAPIValidAuthorizationEndpointRequestObject(username, bindingMessage);
    String encodedRequestObject = registerSharedAuthenticationRequest(requestObject, clientId, Algorithm.PS256);
    // user Backchannel Authentication Request
    AuthenticationRequestAcknowledgement response = doBackchannelAuthenticationRequestWithMTLS(clientId, encodedRequestObject, () -> MutualTLSUtils.newCloseableHttpClientWithDefaultKeyStoreAndTrustStore());
    assertThat(response.getStatusCode(), is(equalTo(200)));
    // user Authentication Channel Request
    TestAuthenticationChannelRequest testRequest = doAuthenticationChannelRequest(bindingMessage);
    AuthenticationChannelRequest authenticationChannelReq = testRequest.getRequest();
    assertThat(authenticationChannelReq.getBindingMessage(), is(equalTo(bindingMessage)));
    assertThat(authenticationChannelReq.getScope(), is(containsString(OAuth2Constants.SCOPE_OPENID)));
    // user Authentication Channel completed
    doAuthenticationChannelCallback(testRequest);
    // user Token Request
    OAuthClient.AccessTokenResponse tokenRes = doBackchannelAuthenticationTokenRequestWithMTLS(clientId, response.getAuthReqId(), () -> MutualTLSUtils.newCloseableHttpClientWithDefaultKeyStoreAndTrustStore());
    verifyBackchannelAuthenticationTokenRequest(tokenRes, clientId, username);
    // Logout and remove consent of the user for next logins
    logoutUserAndRevokeConsent(clientId, username);
}
Also used : OIDCAdvancedConfigWrapper(org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper) OAuthClient(org.keycloak.testsuite.util.OAuthClient) AuthorizationEndpointRequestObject(org.keycloak.testsuite.rest.resource.TestingOIDCEndpointsApplicationResource.AuthorizationEndpointRequestObject) ClientResource(org.keycloak.admin.client.resource.ClientResource) AuthenticationChannelRequest(org.keycloak.protocol.oidc.grants.ciba.channel.AuthenticationChannelRequest) TestAuthenticationChannelRequest(org.keycloak.testsuite.rest.representation.TestAuthenticationChannelRequest) Matchers.containsString(org.hamcrest.Matchers.containsString) AuthenticationRequestAcknowledgement(org.keycloak.testsuite.util.OAuthClient.AuthenticationRequestAcknowledgement) TestAuthenticationChannelRequest(org.keycloak.testsuite.rest.representation.TestAuthenticationChannelRequest) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) Test(org.junit.Test)

Example 4 with AuthenticationChannelRequest

use of org.keycloak.protocol.oidc.grants.ciba.channel.AuthenticationChannelRequest in project keycloak by keycloak.

the class CIBATest method testPingModeSuccess.

@Test
public void testPingModeSuccess() throws Exception {
    ClientResource clientResource = null;
    ClientRepresentation clientRep = null;
    try {
        final String username = "nutzername-rot";
        final String bindingMessage = "BASTION_PING";
        final String clientNotificationToken = "client-notification-token-1";
        Map<String, String> additionalParameters = new HashMap<>();
        additionalParameters.put("user_device", "mobile");
        // prepare CIBA settings
        clientResource = ApiUtil.findClientByClientId(adminClient.realm(TEST_REALM_NAME), TEST_CLIENT_NAME);
        assertThat(clientResource, notNullValue());
        clientRep = clientResource.toRepresentation();
        prepareCIBASettings(clientResource, clientRep, "ping");
        long startTime = Time.currentTime();
        // user Backchannel Authentication Request
        AuthenticationRequestAcknowledgement response = doBackchannelAuthenticationRequest(TEST_CLIENT_NAME, TEST_CLIENT_PASSWORD, username, bindingMessage, clientNotificationToken, additionalParameters);
        // Even in the ping mode should be interval set according to the CIBA specification
        Assert.assertTrue(response.getInterval() > 0);
        // user Authentication Channel Request
        TestAuthenticationChannelRequest testRequest = doAuthenticationChannelRequest(bindingMessage);
        AuthenticationChannelRequest authenticationChannelReq = testRequest.getRequest();
        assertThat(authenticationChannelReq.getBindingMessage(), is(equalTo(bindingMessage)));
        assertThat(authenticationChannelReq.getScope(), is(containsString(OAuth2Constants.SCOPE_OPENID)));
        assertThat(authenticationChannelReq.getAdditionalParameters().get("user_device"), is(equalTo("mobile")));
        // Check clientNotification not yet available
        ClientNotificationEndpointRequest pushedClientNotification = testingClient.testApp().oidcClientEndpoints().getPushedCibaClientNotification(clientNotificationToken);
        Assert.assertNull(pushedClientNotification.getAuthReqId());
        // user Authentication Channel completed
        EventRepresentation loginEvent = doAuthenticationChannelCallback(testRequest);
        String sessionId = loginEvent.getSessionId();
        String codeId = loginEvent.getDetails().get(Details.CODE_ID);
        String userId = loginEvent.getUserId();
        // Check clientNotification exists now for our authReqId
        pushedClientNotification = testingClient.testApp().oidcClientEndpoints().getPushedCibaClientNotification(clientNotificationToken);
        Assert.assertEquals(pushedClientNotification.getAuthReqId(), response.getAuthReqId());
        // user Token Request
        OAuthClient.AccessTokenResponse tokenRes = doBackchannelAuthenticationTokenRequest(username, response.getAuthReqId());
        IDToken idToken = oauth.verifyIDToken(tokenRes.getIdToken());
        long currentTime = Time.currentTime();
        long authTime = idToken.getAuth_time().longValue();
        assertTrue(startTime - 5 <= authTime);
        assertTrue(authTime <= currentTime + 5);
        // token introspection
        String tokenResponse = doIntrospectAccessTokenWithClientCredential(tokenRes, username);
        // token refresh
        tokenRes = doRefreshTokenRequest(tokenRes.getRefreshToken(), username, sessionId, false);
        // token introspection after token refresh
        tokenResponse = doIntrospectAccessTokenWithClientCredential(tokenRes, username);
        // logout by refresh token
        EventRepresentation logoutEvent = doLogoutByRefreshToken(tokenRes.getRefreshToken(), sessionId, userId, false);
    } finally {
        revertCIBASettings(clientResource, clientRep);
    }
}
Also used : HashMap(java.util.HashMap) OAuthClient(org.keycloak.testsuite.util.OAuthClient) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) Matchers.containsString(org.hamcrest.Matchers.containsString) AuthenticationRequestAcknowledgement(org.keycloak.testsuite.util.OAuthClient.AuthenticationRequestAcknowledgement) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) ClientNotificationEndpointRequest(org.keycloak.protocol.oidc.grants.ciba.endpoints.ClientNotificationEndpointRequest) ClientResource(org.keycloak.admin.client.resource.ClientResource) AuthenticationChannelRequest(org.keycloak.protocol.oidc.grants.ciba.channel.AuthenticationChannelRequest) TestAuthenticationChannelRequest(org.keycloak.testsuite.rest.representation.TestAuthenticationChannelRequest) IDToken(org.keycloak.representations.IDToken) TestAuthenticationChannelRequest(org.keycloak.testsuite.rest.representation.TestAuthenticationChannelRequest) Test(org.junit.Test)

Example 5 with AuthenticationChannelRequest

use of org.keycloak.protocol.oidc.grants.ciba.channel.AuthenticationChannelRequest in project keycloak by keycloak.

the class CIBATest method testClientScopesCondition.

@Test
public void testClientScopesCondition() throws Exception {
    String username = "nutzername-rot";
    String bindingMessage = "ThisIsBindingMessage";
    Map<String, String> additionalParameters = new HashMap<>();
    additionalParameters.put("user_device", "mobile");
    String clientConfidentialId = generateSuffixedName("confidential-app");
    String clientConfidentialSecret = "app-secret";
    String cidConfidential = createClientByAdmin(clientConfidentialId, (ClientRepresentation clientRep) -> {
        clientRep.setSecret(clientConfidentialSecret);
        clientRep.setStandardFlowEnabled(Boolean.TRUE);
        clientRep.setImplicitFlowEnabled(Boolean.TRUE);
        clientRep.setPublicClient(Boolean.FALSE);
        clientRep.setBearerOnly(Boolean.FALSE);
        Map<String, String> attributes = Optional.ofNullable(clientRep.getAttributes()).orElse(new HashMap<>());
        attributes.put(CibaConfig.CIBA_BACKCHANNEL_TOKEN_DELIVERY_MODE_PER_CLIENT, "poll");
        attributes.put(CibaConfig.OIDC_CIBA_GRANT_ENABLED, Boolean.TRUE.toString());
        clientRep.setAttributes(attributes);
    });
    oauth.clientId(clientConfidentialId);
    oauth.scope("microprofile-jwt");
    // register profiles
    String json = (new ClientProfilesBuilder()).addProfile((new ClientProfileBuilder()).createProfile(PROFILE_NAME, "Het Eerste Profiel").addExecutor(TestRaiseExeptionExecutorFactory.PROVIDER_ID, null).toRepresentation()).toString();
    updateProfiles(json);
    // register policies
    json = (new ClientPoliciesBuilder()).addPolicy((new ClientPolicyBuilder()).createPolicy(POLICY_NAME, "Het Eerste Beleid", Boolean.TRUE).addCondition(ClientScopesConditionFactory.PROVIDER_ID, createClientScopesConditionConfig(ClientScopesConditionFactory.OPTIONAL, Arrays.asList("microprofile-jwt"))).addProfile(PROFILE_NAME).toRepresentation()).toString();
    updatePolicies(json);
    // user Backchannel Authentication Request
    AuthenticationRequestAcknowledgement response = oauth.doBackchannelAuthenticationRequest(clientConfidentialId, clientConfidentialSecret, username, bindingMessage, null, null, additionalParameters);
    assertThat(response.getStatusCode(), is(equalTo(400)));
    assertThat(response.getError(), is(ClientPolicyEvent.BACKCHANNEL_AUTHENTICATION_REQUEST.name()));
    assertThat(response.getErrorDescription(), is("Exception thrown intentionally"));
    updatePolicies("{}");
    response = oauth.doBackchannelAuthenticationRequest(clientConfidentialId, clientConfidentialSecret, username, bindingMessage, null, null, additionalParameters);
    assertThat(response.getStatusCode(), is(equalTo(200)));
    Assert.assertNotNull(response.getAuthReqId());
    json = (new ClientPoliciesBuilder()).addPolicy((new ClientPolicyBuilder()).createPolicy(POLICY_NAME, "Het Eerste Beleid", Boolean.TRUE).addCondition(ClientScopesConditionFactory.PROVIDER_ID, createClientScopesConditionConfig(ClientScopesConditionFactory.OPTIONAL, Arrays.asList("microprofile-jwt"))).addProfile(PROFILE_NAME).toRepresentation()).toString();
    updatePolicies(json);
    OAuthClient.AccessTokenResponse tokenRes = oauth.doBackchannelAuthenticationTokenRequest(clientConfidentialId, clientConfidentialSecret, response.getAuthReqId());
    assertThat(tokenRes.getStatusCode(), is(equalTo(400)));
    assertThat(tokenRes.getError(), is(OAuthErrorException.INVALID_GRANT));
    assertThat(tokenRes.getErrorDescription(), is("Exception thrown intentionally"));
    updatePolicies("{}");
    // user Authentication Channel Request
    TestAuthenticationChannelRequest testRequest = doAuthenticationChannelRequest(bindingMessage);
    AuthenticationChannelRequest authenticationChannelReq = testRequest.getRequest();
    assertThat(authenticationChannelReq.getBindingMessage(), is(equalTo(bindingMessage)));
    assertThat(authenticationChannelReq.getScope(), is(containsString(OAuth2Constants.SCOPE_OPENID)));
    assertThat(authenticationChannelReq.getAdditionalParameters().get("user_device"), is(equalTo("mobile")));
    // user Authentication Channel completed
    doAuthenticationChannelCallback(testRequest);
    tokenRes = oauth.doBackchannelAuthenticationTokenRequest(clientConfidentialId, clientConfidentialSecret, response.getAuthReqId());
    assertThat(tokenRes.getStatusCode(), is(equalTo(200)));
    AccessToken accessToken = oauth.verifyToken(tokenRes.getAccessToken());
    assertThat(accessToken.getIssuedFor(), is(equalTo(clientConfidentialId)));
    RefreshToken refreshToken = oauth.parseRefreshToken(tokenRes.getRefreshToken());
    assertThat(refreshToken.getIssuedFor(), is(equalTo(clientConfidentialId)));
    assertThat(refreshToken.getAudience()[0], is(equalTo(refreshToken.getIssuer())));
    IDToken idToken = oauth.verifyIDToken(tokenRes.getIdToken());
    assertThat(idToken.getPreferredUsername(), is(equalTo(username)));
    assertThat(idToken.getIssuedFor(), is(equalTo(clientConfidentialId)));
    assertThat(idToken.getAudience()[0], is(equalTo(idToken.getIssuedFor())));
}
Also used : HashMap(java.util.HashMap) OAuthClient(org.keycloak.testsuite.util.OAuthClient) ClientProfilesBuilder(org.keycloak.testsuite.util.ClientPoliciesUtil.ClientProfilesBuilder) ClientPoliciesBuilder(org.keycloak.testsuite.util.ClientPoliciesUtil.ClientPoliciesBuilder) ClientPolicyBuilder(org.keycloak.testsuite.util.ClientPoliciesUtil.ClientPolicyBuilder) Matchers.containsString(org.hamcrest.Matchers.containsString) AuthenticationRequestAcknowledgement(org.keycloak.testsuite.util.OAuthClient.AuthenticationRequestAcknowledgement) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) ClientProfileBuilder(org.keycloak.testsuite.util.ClientPoliciesUtil.ClientProfileBuilder) RefreshToken(org.keycloak.representations.RefreshToken) AccessToken(org.keycloak.representations.AccessToken) AuthenticationChannelRequest(org.keycloak.protocol.oidc.grants.ciba.channel.AuthenticationChannelRequest) TestAuthenticationChannelRequest(org.keycloak.testsuite.rest.representation.TestAuthenticationChannelRequest) IDToken(org.keycloak.representations.IDToken) TestAuthenticationChannelRequest(org.keycloak.testsuite.rest.representation.TestAuthenticationChannelRequest) Test(org.junit.Test)

Aggregations

Matchers.containsString (org.hamcrest.Matchers.containsString)9 AuthenticationChannelRequest (org.keycloak.protocol.oidc.grants.ciba.channel.AuthenticationChannelRequest)9 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)9 TestAuthenticationChannelRequest (org.keycloak.testsuite.rest.representation.TestAuthenticationChannelRequest)9 AuthenticationRequestAcknowledgement (org.keycloak.testsuite.util.OAuthClient.AuthenticationRequestAcknowledgement)9 ClientResource (org.keycloak.admin.client.resource.ClientResource)8 OAuthClient (org.keycloak.testsuite.util.OAuthClient)8 Test (org.junit.Test)7 OIDCClientRepresentation (org.keycloak.representations.oidc.OIDCClientRepresentation)6 AuthorizationEndpointRequestObject (org.keycloak.testsuite.rest.resource.TestingOIDCEndpointsApplicationResource.AuthorizationEndpointRequestObject)5 HashMap (java.util.HashMap)4 IDToken (org.keycloak.representations.IDToken)3 EventRepresentation (org.keycloak.representations.idm.EventRepresentation)3 ClientPoliciesBuilder (org.keycloak.testsuite.util.ClientPoliciesUtil.ClientPoliciesBuilder)3 ClientPolicyBuilder (org.keycloak.testsuite.util.ClientPoliciesUtil.ClientPolicyBuilder)3 ClientProfileBuilder (org.keycloak.testsuite.util.ClientPoliciesUtil.ClientProfileBuilder)3 ClientProfilesBuilder (org.keycloak.testsuite.util.ClientPoliciesUtil.ClientProfilesBuilder)3 KeyPair (java.security.KeyPair)2 PrivateKey (java.security.PrivateKey)2 PublicKey (java.security.PublicKey)2