|
| 1 | +package com.github.skjolber.bench.fusionauth; |
| 2 | + |
| 3 | +import java.security.KeyPair; |
| 4 | + |
| 5 | +import com.github.skjolber.bench.utils.JsonWebTokenVerifier; |
| 6 | + |
| 7 | +import io.fusionauth.jwt.InvalidJWTException; |
| 8 | +import io.fusionauth.jwt.JWTDecoder; |
| 9 | +import io.fusionauth.jwt.Verifier; |
| 10 | +import io.fusionauth.jwt.domain.Algorithm; |
| 11 | +import io.fusionauth.jwt.domain.JWT; |
| 12 | +import io.fusionauth.jwt.rsa.RSAVerifier; |
| 13 | +import io.fusionauth.pem.domain.PEM; |
| 14 | + |
| 15 | +public class FusionAuthJsonWebTokenVerifier implements JsonWebTokenVerifier<JWT> { |
| 16 | + |
| 17 | + private final static Verifier nullVerifier = new Verifier() { |
| 18 | + |
| 19 | + @Override |
| 20 | + public void verify(Algorithm algorithm, byte[] message, byte[] signature) { |
| 21 | + // noop |
| 22 | + } |
| 23 | + |
| 24 | + @Override |
| 25 | + public boolean canVerify(Algorithm algorithm) { |
| 26 | + return true; |
| 27 | + } |
| 28 | + }; |
| 29 | + |
| 30 | + private final RSAVerifier verifier; |
| 31 | + private final JWTDecoder decoder; |
| 32 | + private final String issuer; |
| 33 | + private final String audience; |
| 34 | + |
| 35 | + public FusionAuthJsonWebTokenVerifier(KeyPair keyPair, String issuer, String audience) { |
| 36 | + this.issuer = issuer; |
| 37 | + this.audience = audience; |
| 38 | + |
| 39 | + String encode = PEM.encode(keyPair.getPublic()); |
| 40 | + |
| 41 | + decoder = JWT.getDecoder(); |
| 42 | + verifier = RSAVerifier.newVerifier(encode); |
| 43 | + } |
| 44 | + |
| 45 | + @Override |
| 46 | + public JWT verifyJsonWebToken(String token) { |
| 47 | + JWT jwt = decoder.decode(token, verifier); |
| 48 | + |
| 49 | + // lets add some claim verification here; the other implementations do this already |
| 50 | + if(!issuer.equals(jwt.getString("iss"))) { |
| 51 | + throw new InvalidJWTException("Unexpected issuer"); |
| 52 | + } |
| 53 | + |
| 54 | + if(!audience.equals(jwt.getString("aud"))) { |
| 55 | + throw new InvalidJWTException("Unexpected audience"); |
| 56 | + } |
| 57 | + |
| 58 | + return jwt; |
| 59 | + } |
| 60 | + |
| 61 | + public JWT parseToken(String token) throws Exception { |
| 62 | + return decoder.decode(token, nullVerifier); |
| 63 | + } |
| 64 | +} |
0 commit comments