1414import java .security .spec .X509EncodedKeySpec ;
1515import java .util .Base64 ;
1616
17+ // A JWT(https://datatracker.ietf.org/doc/html/rfc7519) based authorizer,
1718public class JwtAuthorizer implements Authorizer {
1819
1920 private final PublicKey publicKey ;
2021 private final JWTVerifier verifier ;
2122
22- public static final String BEARER_PREFIX = "Bearer " ;
23+ private static final String BEARER_PREFIX = "Bearer " ;
24+ private static final int MAX_USER_TOKEN_LENGTH = 120 ;
2325
24- public JwtAuthorizer (String pemFormatPublicKey ) throws Exception {
25- this .publicKey = loadPublicKey (pemFormatPublicKey );
26+ // `pemFormatRSAPublicKey` is RSA public key used by JWT Auth server for creating signed JWT tokens.
27+ // Refer to OpenSSL(https://docs.openssl.org/1.1.1/man1/rsa/) docs for generating valid key pairs.
28+ // Example:
29+ // * To generate private key, run : `openssl genpkey -algorithm RSA -out private_key.pem -pkeyopt rsa_keygen_bits:2048`
30+ // * To generate public key, run: `openssl rsa -pubout -in private_key.pem -out public_key.pem`
31+ public JwtAuthorizer (String pemFormatRSAPublicKey ) throws Exception {
32+ this .publicKey = loadPublicKey (pemFormatRSAPublicKey );
2633
2734 Algorithm algorithm = Algorithm .RSA256 ((RSAPublicKey ) publicKey , null );
2835 this .verifier = JWT .require (algorithm ).build ();
@@ -47,6 +54,8 @@ public AuthResponse verify(HttpHeaders headers) throws AuthException {
4754
4855 if (userToken == null || userToken .isBlank ()) {
4956 throw new AuthException ("Invalid JWT token." );
57+ } else if (userToken .length () > MAX_USER_TOKEN_LENGTH ) {
58+ throw new AuthException ("UserToken is too long" );
5059 }
5160
5261 return new AuthResponse (userToken );
@@ -56,8 +65,8 @@ public AuthResponse verify(HttpHeaders headers) throws AuthException {
5665 }
5766 }
5867
59- private PublicKey loadPublicKey (String pemFormatPublicKey ) throws Exception {
60- String key = pemFormatPublicKey
68+ private PublicKey loadPublicKey (String pemFormatRSAPublicKey ) throws Exception {
69+ String key = pemFormatRSAPublicKey
6170 .replaceAll ("\\ n" , "" )
6271 .replace ("-----BEGIN PUBLIC KEY-----" , "" )
6372 .replace ("-----END PUBLIC KEY-----" , "" );
0 commit comments