io.jsonwebtoken.JwtException Java Examples

The following examples show how to use io.jsonwebtoken.JwtException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JwtIdentityProvider.java    From nifi-registry with Apache License 2.0 6 votes vote down vote up
@Override
public AuthenticationResponse authenticate(AuthenticationRequest authenticationRequest) throws InvalidCredentialsException, IdentityAccessException {

    if (authenticationRequest == null) {
        logger.info("Cannot authenticate null authenticationRequest, returning null.");
        return null;
    }

    final Object credentials = authenticationRequest.getCredentials();
    String jwtAuthToken = credentials != null && credentials instanceof String ? (String) credentials : null;

    if (credentials == null) {
        logger.info("JWT not found in authenticationRequest credentials, returning null.");
        return null;
    }

    try {
        final String jwtPrincipal = jwtService.getAuthenticationFromToken(jwtAuthToken);
        return new AuthenticationResponse(jwtPrincipal, jwtPrincipal, expiration, issuer);
    } catch (JwtException e) {
        throw new InvalidAuthenticationException(e.getMessage(), e);
    }
}
 
Example #2
Source File: JwtService.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private Jws<Claims> parseTokenFromBase64EncodedString(final String base64EncodedToken) throws JwtException {
    try {
        return Jwts.parser().setSigningKeyResolver(new SigningKeyResolverAdapter() {
            @Override
            public byte[] resolveSigningKeyBytes(JwsHeader header, Claims claims) {
                final String identity = claims.getSubject();

                // Get the key based on the key id in the claims
                final Integer keyId = claims.get(KEY_ID_CLAIM, Integer.class);
                final Key key = keyService.getKey(keyId);

                // Ensure we were able to find a key that was previously issued by this key service for this user
                if (key == null || key.getKey() == null) {
                    throw new UnsupportedJwtException("Unable to determine signing key for " + identity + " [kid: " + keyId + "]");
                }

                return key.getKey().getBytes(StandardCharsets.UTF_8);
            }
        }).parseClaimsJws(base64EncodedToken);
    } catch (final MalformedJwtException | UnsupportedJwtException | SignatureException | ExpiredJwtException | IllegalArgumentException | AdministrationException e) {
        // TODO: Exercise all exceptions to ensure none leak key material to logs
        final String errorMessage = "Unable to validate the access token.";
        throw new JwtException(errorMessage, e);
    }
}
 
Example #3
Source File: OpenIdAuthorizer.java    From incubator-iotdb with Apache License 2.0 6 votes vote down vote up
/**
 * So not with the token!
 * @param token Usually the JWT but could also be just the name of the user ({@link #getUsername(String)}.
 * @return true if the user is an admin
 */
@Override
boolean isAdmin(String token) {
    Claims claims;
    if (this.loggedClaims.containsKey(token)) {
        // This is a username!
        claims = this.loggedClaims.get(token);
    } else {
        // Its a token
        try {
            claims = validateToken(token);
        } catch (JwtException e) {
            logger.warn("Unable to validate token {}!", token, e);
            return false;
        }
    }
    // Get available roles (from keycloack)
    List<String> availableRoles = ((Map<String, List<String>>) claims.get("realm_access")).get("roles");
    if (!availableRoles.contains(IOTDB_ADMIN_ROLE_NAME)) {
        logger.warn("Given Token has no admin rights, is there a ROLE with name {} in 'realm_access' role set?", IOTDB_ADMIN_ROLE_NAME);
        return false;
    }
    return true;
}
 
Example #4
Source File: JwtServiceTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testShouldLogOutUser() throws Exception {
    // Arrange
    expectedException.expect(JwtException.class);
    expectedException.expectMessage("Unable to validate the access token.");

    // Token expires in 60 seconds
    final int EXPIRATION_MILLIS = 60000;
    LoginAuthenticationToken loginAuthenticationToken = new LoginAuthenticationToken(DEFAULT_IDENTITY,
            EXPIRATION_MILLIS,
            "MockIdentityProvider");
    logger.debug("Generating token for " + loginAuthenticationToken);

    // Act
    String token = jwtService.generateSignedToken(loginAuthenticationToken);
    logger.debug("Generated JWT: " + token);
    String authID = jwtService.getAuthenticationFromToken(token);
    assertEquals(DEFAULT_IDENTITY, authID);
    logger.debug("Logging out user: " + DEFAULT_IDENTITY);
    jwtService.logOut(token);
    logger.debug("Logged out user: " + DEFAULT_IDENTITY);
    jwtService.getAuthenticationFromToken(token);

    // Assert
    // Should throw exception when user is not found
}
 
Example #5
Source File: JwtService.java    From nifi with Apache License 2.0 6 votes vote down vote up
private Jws<Claims> parseTokenFromBase64EncodedString(final String base64EncodedToken) throws JwtException {
    try {
        return Jwts.parser().setSigningKeyResolver(new SigningKeyResolverAdapter() {
            @Override
            public byte[] resolveSigningKeyBytes(JwsHeader header, Claims claims) {
                final String identity = claims.getSubject();

                // Get the key based on the key id in the claims
                final Integer keyId = claims.get(KEY_ID_CLAIM, Integer.class);
                final Key key = keyService.getKey(keyId);

                // Ensure we were able to find a key that was previously issued by this key service for this user
                if (key == null || key.getKey() == null) {
                    throw new UnsupportedJwtException("Unable to determine signing key for " + identity + " [kid: " + keyId + "]");
                }

                return key.getKey().getBytes(StandardCharsets.UTF_8);
            }
        }).parseClaimsJws(base64EncodedToken);
    } catch (final MalformedJwtException | UnsupportedJwtException | SignatureException | ExpiredJwtException | IllegalArgumentException | AdministrationException e) {
        // TODO: Exercise all exceptions to ensure none leak key material to logs
        final String errorMessage = "Unable to validate the access token.";
        throw new JwtException(errorMessage, e);
    }
}
 
Example #6
Source File: JwksAuthenticator.java    From trellis with Apache License 2.0 6 votes vote down vote up
@Override
public Claims parse(final String token) {
    return Jwts.parserBuilder().setSigningKeyResolver(new SigningKeyResolverAdapter() {
        @Override
        public Key resolveSigningKey(final JwsHeader header, final Claims claims) {
            final String keyid = header.getKeyId();
            if (keyid == null) {
                throw new JwtException("Missing Key ID (kid) header field");
            }
            if (keys.containsKey(keyid)) {
                return keys.get(keyid);
            }
            throw new SecurityException("Could not locate key: " + keyid);
        }
    }).build().parseClaimsJws(token).getBody();
}
 
Example #7
Source File: FederatedJwtAuthenticator.java    From trellis with Apache License 2.0 6 votes vote down vote up
@Override
public Claims parse(final String credentials) {
    // Parse the JWT claims
    return Jwts.parserBuilder().setSigningKeyResolver(new SigningKeyResolverAdapter() {
        @Override
        public Key resolveSigningKey(final JwsHeader header, final Claims claims) {
            if (header.getKeyId() == null) {
                throw new JwtException("Missing Key ID (kid) header field");
            }
            try {
                if (keyIds.contains(header.getKeyId()) && keyStore.containsAlias(header.getKeyId())) {
                    return keyStore.getCertificate(header.getKeyId()).getPublicKey();
                }
            } catch (final KeyStoreException ex) {
                throw new SecurityException("Error retrieving key from keystore", ex);
            }
            throw new SecurityException("Could not locate key in keystore: " + header.getKeyId());
        }
    }).build().parseClaimsJws(credentials).getBody();
}
 
Example #8
Source File: JwtService.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
public String getAuthenticationFromToken(final String base64EncodedToken) throws JwtException {
    // The library representations of the JWT should be kept internal to this service.
    try {
        final Jws<Claims> jws = parseTokenFromBase64EncodedString(base64EncodedToken);

        if (jws == null) {
            throw new JwtException("Unable to parse token");
        }

        // Additional validation that subject is present
        if (StringUtils.isEmpty(jws.getBody().getSubject())) {
            throw new JwtException("No subject available in token");
        }

        // TODO: Validate issuer against active registry?
        if (StringUtils.isEmpty(jws.getBody().getIssuer())) {
            throw new JwtException("No issuer available in token");
        }
        return jws.getBody().getSubject();
    } catch (JwtException e) {
        logger.debug("The Base64 encoded JWT: " + base64EncodedToken);
        final String errorMessage = "There was an error validating the JWT";
        logger.error(errorMessage, e);
        throw e;
    }
}
 
Example #9
Source File: JwtService.java    From nifi-registry with Apache License 2.0 6 votes vote down vote up
private Jws<Claims> parseTokenFromBase64EncodedString(final String base64EncodedToken) throws JwtException {
    try {
        return Jwts.parser().setSigningKeyResolver(new SigningKeyResolverAdapter() {
            @Override
            public byte[] resolveSigningKeyBytes(JwsHeader header, Claims claims) {
                final String identity = claims.getSubject();

                // Get the key based on the key id in the claims
                final String keyId = claims.get(KEY_ID_CLAIM, String.class);
                final Key key = keyService.getKey(keyId);

                // Ensure we were able to find a key that was previously issued by this key service for this user
                if (key == null || key.getKey() == null) {
                    throw new UnsupportedJwtException("Unable to determine signing key for " + identity + " [kid: " + keyId + "]");
                }

                return key.getKey().getBytes(StandardCharsets.UTF_8);
            }
        }).parseClaimsJws(base64EncodedToken);
    } catch (final MalformedJwtException | UnsupportedJwtException | SignatureException | ExpiredJwtException | IllegalArgumentException e) {
        // TODO: Exercise all exceptions to ensure none leak key material to logs
        final String errorMessage = "Unable to validate the access token.";
        throw new JwtException(errorMessage, e);
    }
}
 
Example #10
Source File: JwtService.java    From nifi-registry with Apache License 2.0 6 votes vote down vote up
public String getAuthenticationFromToken(final String base64EncodedToken) throws JwtException {
    // The library representations of the JWT should be kept internal to this service.
    try {
        final Jws<Claims> jws = parseTokenFromBase64EncodedString(base64EncodedToken);

        if (jws == null) {
            throw new JwtException("Unable to parse token");
        }

        // Additional validation that subject is present
        if (StringUtils.isEmpty(jws.getBody().getSubject())) {
            throw new JwtException("No subject available in token");
        }

        // TODO: Validate issuer against active IdentityProvider?
        if (StringUtils.isEmpty(jws.getBody().getIssuer())) {
            throw new JwtException("No issuer available in token");
        }
        return jws.getBody().getSubject();
    } catch (JwtException e) {
        logger.debug("The Base64 encoded JWT: " + base64EncodedToken);
        final String errorMessage = "There was an error validating the JWT";
        logger.error(errorMessage, e);
        throw e;
    }
}
 
Example #11
Source File: JwtServiceTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Test(expected = JwtException.class)
public void testShouldNotGenerateTokenWithMissingKey() throws Exception {
    // Arrange
    final int EXPIRATION_MILLIS = 60000;
    LoginAuthenticationToken loginAuthenticationToken = new LoginAuthenticationToken("alopresto",
            EXPIRATION_MILLIS,
            "MockIdentityProvider");
    logger.debug("Generating token for " + loginAuthenticationToken);

    // Set up the bad key service
    KeyService missingKeyService = Mockito.mock(KeyService.class);
    when(missingKeyService.getOrCreateKey(anyString())).thenThrow(new AdministrationException("Could not find a "
            + "key for that user"));
    jwtService = new JwtService(missingKeyService);

    // Act
    jwtService.generateSignedToken(loginAuthenticationToken);

    // Assert
    // Should throw exception
}
 
Example #12
Source File: JwtTokenVerifier.java    From james-project with Apache License 2.0 5 votes vote down vote up
public boolean hasAttribute(String attributeName, Object expectedValue, String token) {
    try {
        Jwts
            .parser()
            .require(attributeName, expectedValue)
            .setSigningKey(pubKeyProvider.get())
            .parseClaimsJws(token);
        return true;
    } catch (JwtException e) {
        LOGGER.info("Jwt validation failed for claim {} to {}", attributeName, expectedValue, e);
        return false;
    }
}
 
Example #13
Source File: JwtTokenVerifier.java    From james-project with Apache License 2.0 5 votes vote down vote up
public boolean verify(String token) {
    try {
        String subject = extractLogin(token);
        if (Strings.isNullOrEmpty(subject)) {
            throw new MalformedJwtException("'subject' field in token is mandatory");
        }
        return true;
    } catch (JwtException e) {
        LOGGER.info("Failed Jwt verification", e);
        return false;
    }
}
 
Example #14
Source File: JwtServiceTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testLogoutWhenAuthTokenIsEmptyShouldThrowError() throws Exception {
    // Arrange
    expectedException.expect(JwtException.class);
    expectedException.expectMessage("Log out failed: The user identity was not present in the request token to log out user.");

    // Act
    jwtService.logOut(null);

    // Assert
    // Should throw exception when authorization header is null
}
 
Example #15
Source File: JwtServiceTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test(expected = JwtException.class)
public void testShouldNotGetAuthenticationForExpiredToken() throws Exception {
    // Arrange
    String token = EXPIRED_SIGNED_TOKEN;

    // Act
    String identity = jwtService.getAuthenticationFromToken(token);
    logger.debug("Extracted identity: " + identity);

    // Assert
    // Should fail
}
 
Example #16
Source File: EllipticCurveSigner.java    From jjwt with Apache License 2.0 5 votes vote down vote up
protected byte[] doSign(byte[] data) throws InvalidKeyException, java.security.SignatureException, JwtException {
    PrivateKey privateKey = (PrivateKey)key;
    Signature sig = createSignatureInstance();
    sig.initSign(privateKey);
    sig.update(data);
    return transcodeSignatureToConcat(sig.sign(), getSignatureByteArrayLength(alg));
}
 
Example #17
Source File: EllipticCurveProvider.java    From jjwt with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the expected signature byte array length (R + S parts) for
 * the specified ECDSA algorithm.
 *
 * @param alg The ECDSA algorithm. Must be supported and not
 *            {@code null}.
 * @return The expected byte array length for the signature.
 * @throws JwtException If the algorithm is not supported.
 */
public static int getSignatureByteArrayLength(final SignatureAlgorithm alg)
    throws JwtException {

    switch (alg) {
        case ES256:
            return 64;
        case ES384:
            return 96;
        case ES512:
            return 132;
        default:
            throw new JwtException("Unsupported Algorithm: " + alg.name());
    }
}
 
Example #18
Source File: JwtAuthenticationProvider.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    final JwtAuthenticationRequestToken request = (JwtAuthenticationRequestToken) authentication;

    try {
        final String jwtPrincipal = jwtService.getAuthenticationFromToken(request.getToken());
        final String mappedIdentity = mapIdentity(jwtPrincipal);
        final NiFiUser user = new Builder().identity(mappedIdentity).groups(getUserGroups(mappedIdentity)).clientAddress(request.getClientAddress()).build();
        return new NiFiAuthenticationToken(new NiFiUserDetails(user));
    } catch (JwtException e) {
        throw new InvalidAuthenticationException(e.getMessage(), e);
    }
}
 
Example #19
Source File: JwtService.java    From nifi with Apache License 2.0 5 votes vote down vote up
public String getAuthenticationFromToken(final String base64EncodedToken) throws JwtException {
    // The library representations of the JWT should be kept internal to this service.
    try {
        final Jws<Claims> jws = parseTokenFromBase64EncodedString(base64EncodedToken);

        if (jws == null) {
            throw new JwtException("Unable to parse token");
        }

        // Additional validation that subject is present
        if (StringUtils.isEmpty(jws.getBody().getSubject())) {
            throw new JwtException("No subject available in token");
        }

        // TODO: Validate issuer against active registry?
        if (StringUtils.isEmpty(jws.getBody().getIssuer())) {
            throw new JwtException("No issuer available in token");
        }
        return jws.getBody().getSubject();
    } catch (JwtException e) {
        logger.debug("The Base64 encoded JWT: " + base64EncodedToken);
        final String errorMessage = "There was an error validating the JWT";

        // A common attack is someone trying to use a token after the user is logged out
        // No need to show a stacktrace for an expected and handled scenario
        String causeMessage = e.getLocalizedMessage();
        if (e.getCause() != null) {
            causeMessage += "\n\tCaused by: " + e.getCause().getLocalizedMessage();
        }
        if (logger.isDebugEnabled()) {
            logger.error(errorMessage, e);
        } else {
            logger.error(errorMessage);
            logger.error(causeMessage);
        }
        throw e;
    }
}
 
Example #20
Source File: ApiUtils.java    From auto-subtitle-tool with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 获取当前用户id
 */
public static Long currentUid(String jwt) {
    Key key = Keys.hmacShaKeyFor(EncryConstant.SECRET.getBytes());
    Long userId = null;
    Date expireDate = Jwts.parser().setSigningKey(key).parseClaimsJws(jwt).getBody().getExpiration();
    if (expireDate.getTime() < new Date().getTime()) {
        throw new LoginException(ErrorCodeEnum.AUTHENTICATION_EXPIRE);
    }
    try {
        userId = Long.valueOf(Jwts.parser().setSigningKey(key).parseClaimsJws(jwt).getBody().getId());
    } catch (JwtException e) {
        throw new LoginException(ErrorCodeEnum.UNAUTHORIZED);
    }
    return userId;
}
 
Example #21
Source File: FederatedJwtAuthenticatorTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testAuthenticateKeystoreNoKeyId() throws Exception {
    final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(getClass().getResourceAsStream("/keystore.jks"), passphrase);

    final Key privateKey = ks.getKey("trellis-ec", passphrase);
    final String token = Jwts.builder().setSubject("https://people.apache.org/~acoburn/#i")
        .signWith(privateKey, SignatureAlgorithm.ES256).compact();
    final Authenticator authenticator = new FederatedJwtAuthenticator(ks,
            singletonList("trellis-ec"));

    assertThrows(JwtException.class, () -> authenticator.authenticate(token), "Unexpected key id field!");
}
 
Example #22
Source File: JwtTokenService.java    From secrets-proxy with Apache License 2.0 5 votes vote down vote up
/**
 * Validates and returns the claims of given JWS
 *
 * @param token compact JWS (JSON Web Signature)
 * @return {@link Claims} . Returns <code>null</code> if it fails to verify/expires the JWT.
 */
public @Nullable Claims getClaims(@Nonnull String token) {
  Claims claims;
  try {
    claims =
        Jwts.parser().setSigningKey(String.valueOf(secretKey)).parseClaimsJws(token).getBody();
  } catch (JwtException e) {
    log.debug("JWT token parser error.", e);
    claims = null;
  }
  return claims;
}
 
Example #23
Source File: AccessResource.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
private String createAccessToken(IdentityProvider identityProvider, AuthenticationRequest authenticationRequest)
        throws InvalidCredentialsException, AdministrationException {

    final AuthenticationResponse authenticationResponse;

    try {
        authenticationResponse = identityProvider.authenticate(authenticationRequest);
        final String token = jwtService.generateSignedToken(authenticationResponse);
        return token;
    } catch (final IdentityAccessException | JwtException e) {
        throw new AdministrationException(e.getMessage());
    }

}
 
Example #24
Source File: AccessResource.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
@DELETE
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.WILDCARD)
@Path("/logout")
@ApiOperation(
        value = "Performs a logout for other providers that have been issued a JWT.",
        notes = NON_GUARANTEED_ENDPOINT
)
@ApiResponses(
        value = {
                @ApiResponse(code = 200, message = "User was logged out successfully."),
                @ApiResponse(code = 401, message = "Authentication token provided was empty or not in the correct JWT format."),
                @ApiResponse(code = 500, message = "Client failed to log out."),
        }
)
public Response logOut(@Context HttpServletRequest httpServletRequest, @Context HttpServletResponse httpServletResponse) {
    if (!httpServletRequest.isSecure()) {
        throw new IllegalStateException("User authentication/authorization is only supported when running over HTTPS.");
    }

    String userIdentity = NiFiUserUtils.getNiFiUserIdentity();

    if(userIdentity != null && !userIdentity.isEmpty()) {
        try {
            logger.info("Logging out user " + userIdentity);
            jwtService.logOut(userIdentity);
            return generateOkResponse().build();
        } catch (final JwtException e) {
            logger.error("Logout of user " + userIdentity + " failed due to: " + e.getMessage());
            return Response.serverError().build();
        }
    } else {
        return Response.status(401, "Authentication token provided was empty or not in the correct JWT format.").build();
    }
}
 
Example #25
Source File: JwtService.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
public void logOut(String userIdentity) {
    if (userIdentity == null || userIdentity.isEmpty()) {
        throw new JwtException("Log out failed: The user identity was not present in the request token to log out user.");
    }

    try {
        keyService.deleteKey(userIdentity);
        logger.info("Deleted token from database.");
    } catch (Exception e) {
        logger.error("Unable to log out user: " + userIdentity + ". Failed to remove their token from database.");
        throw e;
    }
}
 
Example #26
Source File: JwtService.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
/**
 * Generates a signed JWT token from the provided IdentityProvider AuthenticationResponse
 *
 * @param authenticationResponse an instance issued by an IdentityProvider after identity claim has been verified as authentic
 * @return a signed JWT containing the user identity and the identity provider, Base64-encoded
 * @throws JwtException if there is a problem generating the signed token
 */
public String generateSignedToken(final AuthenticationResponse authenticationResponse) throws JwtException {
    if (authenticationResponse == null) {
        throw new IllegalArgumentException("Cannot generate a JWT for a null authenticationResponse");
    }

    return generateSignedToken(
            authenticationResponse.getIdentity(),
            authenticationResponse.getUsername(),
            authenticationResponse.getIssuer(),
            authenticationResponse.getIssuer(),
            authenticationResponse.getExpiration());
}
 
Example #27
Source File: JwtTokenStore.java    From ServiceComb-Company-WorkShop with Apache License 2.0 5 votes vote down vote up
@Override
public String parse(String token) {
  try {
    return Jwts.parser()
        .setSigningKey(secretKey)
        .parseClaimsJws(token)
        .getBody()
        .getSubject();
  } catch (JwtException | IllegalArgumentException e) {
    throw new TokenException(e);
  }
}
 
Example #28
Source File: EllipticCurveSigner.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected byte[] doSign(byte[] data) throws InvalidKeyException, java.security.SignatureException, JwtException {
    PrivateKey privateKey = (PrivateKey)key;
    Signature sig = createSignatureInstance();
    sig.initSign(privateKey);
    sig.update(data);
    return transcodeSignatureToConcat(sig.sign(), getSignatureByteArrayLength(alg));
}
 
Example #29
Source File: JwtServiceTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test(expected = JwtException.class)
public void testShouldNotGenerateTokenWithNullIdentity() throws Exception {
    // Arrange
    final int EXPIRATION_MILLIS = 60000;
    LoginAuthenticationToken nullIdentityLoginAuthenticationToken = new LoginAuthenticationToken(null,
            EXPIRATION_MILLIS, "MockIdentityProvider");
    logger.debug("Generating token for " + nullIdentityLoginAuthenticationToken);

    // Act
    jwtService.generateSignedToken(nullIdentityLoginAuthenticationToken);

    // Assert
    // Should throw exception
}
 
Example #30
Source File: EllipticCurveProvider.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the expected signature byte array length (R + S parts) for
 * the specified ECDSA algorithm.
 *
 * @param alg The ECDSA algorithm. Must be supported and not
 *            {@code null}.
 *
 * @return The expected byte array length for the signature.
 *
 * @throws JwtException If the algorithm is not supported.
 */
public static int getSignatureByteArrayLength(final SignatureAlgorithm alg)
        throws JwtException {

    switch (alg) {
        case ES256: return 64;
        case ES384: return 96;
        case ES512: return 132;
        default:
            throw new JwtException("Unsupported Algorithm: " + alg.name());
    }
}