

package net.prasenjit.identity.openid;

import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.oauth2.sdk.ClientCredentialsGrant;
import com.nimbusds.oauth2.sdk.ParseException;
import com.nimbusds.oauth2.sdk.TokenRequest;
import com.nimbusds.oauth2.sdk.TokenResponse;
import com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod;
import com.nimbusds.oauth2.sdk.auth.ClientSecretJWT;
import com.nimbusds.oauth2.sdk.auth.PrivateKeyJWT;
import com.nimbusds.openid.connect.sdk.OIDCTokenResponseParser;
import com.nimbusds.openid.connect.sdk.rp.OIDCClientMetadata;
import net.prasenjit.identity.HtmlPageTestBase;
import org.junit.Test;

import java.io.IOException;

import static org.junit.Assert.*;

public class ClientSecretJWTTest extends HtmlPageTestBase {

    @Override
    protected void configureClient(OIDCClientMetadata metadata) throws JOSEException, ParseException {
        metadata.setTokenEndpointAuthMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT);
        metadata.setTokenEndpointAuthJWSAlg(JWSAlgorithm.HS256);
    }

    @Test
    public void testClientCredentials() throws JOSEException, IOException, ParseException {
        ClientSecretJWT auth = new ClientSecretJWT(clientInformation.getID(), getTokenURI(), JWSAlgorithm.HS256, clientInformation.getSecret());
        ClientCredentialsGrant grant = new ClientCredentialsGrant();
        TokenRequest tokenRequest = new TokenRequest(getTokenURI(), auth, grant);

        TokenResponse tokenResponse = OIDCTokenResponseParser.parse(tokenRequest.toHTTPRequest().send());

        assertTrue(tokenResponse.indicatesSuccess());

        assertNotNull(tokenResponse.toSuccessResponse().getTokens().getBearerAccessToken());
    }

    @Test
    public void testPrivateKeyJWTAuth() throws JOSEException, IOException, ParseException {
        RSAKey rsaKey = (RSAKey) jwkSet.getKeyByKeyId("client-sign");

        PrivateKeyJWT auth = new PrivateKeyJWT(clientInformation.getID(), getTokenURI(), JWSAlgorithm.RS256,
                rsaKey.toRSAPrivateKey(), "client-sign", null);
        ClientCredentialsGrant grant = new ClientCredentialsGrant();
        TokenRequest tokenRequest = new TokenRequest(getTokenURI(), auth, grant);

        TokenResponse tokenResponse = OIDCTokenResponseParser.parse(tokenRequest.toHTTPRequest().send());

        assertFalse(tokenResponse.indicatesSuccess());
    }
}
