Created
July 16, 2021 07:01
-
-
Save amirmv2006/5bd49483b3e310f1a33c343d43965526 to your computer and use it in GitHub Desktop.
Mocked JWT server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ir.amv.enterprise.laas.webapp.common.test.jwt | |
import com.github.tomakehurst.wiremock.WireMockServer | |
import com.github.tomakehurst.wiremock.client.WireMock.aResponse | |
import com.github.tomakehurst.wiremock.client.WireMock.get | |
import com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo | |
import com.github.tomakehurst.wiremock.core.WireMockConfiguration | |
import com.nimbusds.jose.JWSAlgorithm | |
import com.nimbusds.jose.JWSHeader | |
import com.nimbusds.jose.crypto.RSASSASigner | |
import com.nimbusds.jose.jwk.JWKSet | |
import com.nimbusds.jose.jwk.gen.RSAKeyGenerator | |
import com.nimbusds.jose.util.JSONObjectUtils | |
import com.nimbusds.jwt.JWTClaimsSet | |
import com.nimbusds.jwt.SignedJWT | |
import org.junit.jupiter.api.AfterAll | |
import org.springframework.http.HttpHeaders | |
import org.springframework.http.MediaType | |
import java.util.Date | |
open class JwtServingTest { | |
private val rsaJWK = RSAKeyGenerator(2048) | |
.keyID("123") | |
.generate() | |
private val wireMockServer: WireMockServer | |
val port: Int | |
init { | |
// assuming we're not even running Spring! | |
wireMockServer = WireMockServer( | |
WireMockConfiguration() | |
.dynamicPort() | |
) | |
wireMockServer.start() | |
port = wireMockServer.port() | |
wireMockServer.stubFor( | |
get(urlEqualTo("/certs")) | |
.willReturn( | |
aResponse() | |
.withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) | |
.withBody(JSONObjectUtils.toJSONString(JWKSet(rsaJWK).toJSONObject())) | |
) | |
) | |
} | |
fun generateToken(): String { | |
// Create RSA-signer with the private key | |
val signer = RSASSASigner(rsaJWK) | |
// Prepare JWT with claims set | |
val claimsSet = JWTClaimsSet.Builder() | |
.subject("alice") | |
.issuer("https://c2id.com") | |
.expirationTime(Date(Date().time + 60 * 1000)) | |
.build() | |
val signedJWT = SignedJWT( | |
JWSHeader.Builder(JWSAlgorithm.RS256).keyID(rsaJWK.getKeyID()).build(), | |
claimsSet) | |
// Compute the RSA signature | |
signedJWT.sign(signer) | |
// To serialize to compact form, produces something like | |
// eyJhbGciOiJSUzI1NiJ9.SW4gUlNBIHdlIHRydXN0IQ.IRMQENi4nJyp4er2L | |
// mZq3ivwoAjqa1uUkSBKFIX7ATndFF5ivnt-m8uApHO4kfIFOrW7w2Ezmlg3Qd | |
// maXlS9DhN0nUk_hGI3amEjkKd0BWYCB8vfUbUv0XGjQip78AI4z1PrFRNidm7 | |
// -jPDm5Iq0SZnjKjCNS5Q15fokXZc8u0A | |
return signedJWT.serialize() | |
} | |
@AfterAll | |
fun stopServer() { | |
wireMockServer.stop() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment