@Override public Principal authenticate(HttpServletRequest request) throws AuthenticationException { String header = nullToEmpty(request.getHeader(AUTHORIZATION)); int space = header.indexOf(' '); if ((space < 0) || !header.substring(0, space).equalsIgnoreCase("bearer")) { throw needAuthentication(null); } String token = header.substring(space + 1).trim(); if (token.isEmpty()) { throw needAuthentication(null); } try { Jws<Claims> claimsJws = jwtParser.parseClaimsJws(token); String subject = claimsJws.getBody().getSubject(); return new BasicPrincipal(subject); } catch (JwtException e) { throw needAuthentication(e.getMessage()); } catch (RuntimeException e) { throw new RuntimeException("Authentication error", e); } }
throw new JwtException("Invalid ECDSA signature format"); offset = 3; } else { throw new JwtException("Invalid ECDSA signature format"); || derSignature[offset] != 2 || derSignature[offset + 2 + rLength] != 2) { throw new JwtException("Invalid ECDSA signature format");
/** * Tries to parse specified String as a JWT token. If successful, returns User object with username, id and role prefilled (extracted from token). * If unsuccessful (token is invalid or not containing all required user properties), simply returns null. * * @param token the JWT token to parse * @return the User object extracted from specified token or null if a token is invalid. */ public JwtUserDto parseToken(String token) { JwtUserDto u = null; try { Claims body = Jwts.parser() .setSigningKey(secret) .parseClaimsJws(token) .getBody(); u = new JwtUserDto(); u.setUsername(body.getSubject()); u.setRole((String) body.get("role")); } catch (ExpiredJwtException e) { throw new JwtTokenExpiredException(); } catch (JwtException e) { // Simply print the exception and null will be returned for the userDto e.printStackTrace(); } return u; } }
@Override public byte[] sign(byte[] data) { try { return doSign(data); } catch (InvalidKeyException e) { throw new SignatureException("Invalid Elliptic Curve PrivateKey. " + e.getMessage(), e); } catch (java.security.SignatureException e) { throw new SignatureException("Unable to calculate signature using Elliptic Curve PrivateKey. " + e.getMessage(), e); } catch (JwtException e) { throw new SignatureException("Unable to convert signature to JOSE format. " + e.getMessage(), e); } }
throw new JwtException("Invalid ECDSA signature format");
accessStatus.setMessage("You are already logged in."); } catch (JwtException e) { throw new InvalidAuthenticationException(e.getMessage(), e);
/** * 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()); } }
@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); } }
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; } }
private Optional<Principal> authenticate(final String token) { try { return authenticator.authenticate(token); } catch (final SecurityException ex) { LOGGER.debug("Invalid signature, ignoring JWT token: {}", ex.getMessage()); } catch (final JwtException ex) { LOGGER.warn("Problem reading JWT value: {}", ex.getMessage()); } return empty(); }
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); } }
private Claims getClaimsFromToken(String token) { Claims claims = null; try { claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody(); } catch (JwtException e) { log.error(e.getMessage(), e); } return claims; } }
final String errorMessage = "Cannot generate a JWT for a token with an empty identity issued by " + authenticationToken.getIssuer(); logger.error(errorMessage); throw new JwtException(errorMessage); final String errorMessage = "Could not retrieve the signing key for JWT for " + identity; logger.error(errorMessage, e); throw new JwtException(errorMessage, e);
@Override public Principal authenticate(HttpServletRequest request) throws AuthenticationException { String header = nullToEmpty(request.getHeader(AUTHORIZATION)); int space = header.indexOf(' '); if ((space < 0) || !header.substring(0, space).equalsIgnoreCase("bearer")) { throw needAuthentication(null); } String token = header.substring(space + 1).trim(); if (token.isEmpty()) { throw needAuthentication(null); } try { Jws<Claims> claimsJws = jwtParser.parseClaimsJws(token); String subject = claimsJws.getBody().getSubject(); return new BasicPrincipal(subject); } catch (JwtException e) { throw needAuthentication(e.getMessage()); } catch (RuntimeException e) { throw new RuntimeException("Authentication error", e); } }
private void ensureType(String registeredClaim, Object value, Class expectedType) { boolean isCorrectType = expectedType.isInstance(value) || expectedType == Long.class && value instanceof Integer; if (!isCorrectType) { String msg = "Expected type: " + expectedType.getCanonicalName() + " for registered claim: '" + registeredClaim + "', but got value: " + value + " of type: " + value.getClass().getCanonicalName(); throw new JwtException(msg); } } }
/** * Check JWT signature and get claims. * * @param jwt JSON Web Token * @param rsaVerifier Public key to check JWT signature * @return JWT Claims */ private Jws<Claims> getClaims(String jwt, PublicKey rsaVerifier) throws JwtProcessingException { try { return parser.setSigningKey(rsaVerifier).parseClaimsJws(jwt); } catch (JwtException e) { throw new JwtProcessingException(e.getMessage(), e); } }
@Override public Key resolveSigningKey(JwsHeader header, Claims claims) { String kid = header.getKeyId(); if (!Strings.hasText(kid)) { throw new JwtException("Missing required 'kid' header param in JWT with claims: " + claims); } Key key = publicKeys.get(kid); if (key == null) { throw new JwtException("No public key registered for kid: " + kid + ". JWT claims: " + claims); } return key; } };
@Override public Principal authenticate(HttpServletRequest request) throws AuthenticationException { String header = nullToEmpty(request.getHeader(AUTHORIZATION)); int space = header.indexOf(' '); if ((space < 0) || !header.substring(0, space).equalsIgnoreCase("bearer")) { throw needAuthentication(null); } String token = header.substring(space + 1).trim(); if (token.isEmpty()) { throw needAuthentication(null); } try { Jws<Claims> claimsJws = jwtParser.parseClaimsJws(token); String subject = claimsJws.getBody().getSubject(); return new BasicPrincipal(subject); } catch (JwtException e) { throw needAuthentication(e.getMessage()); } catch (RuntimeException e) { throw new RuntimeException("Authentication error", e); } }
throw new JwtException("Invalid ECDSA signature format"); offset = 3; } else { throw new JwtException("Invalid ECDSA signature format"); || derSignature[offset] != 2 || derSignature[offset + 2 + rLength] != 2) { throw new JwtException("Invalid ECDSA signature format");
@Override public Authentication parseJwtToken(String jwtToken) throws AuthenticationException { try { Claims claims = Jwts.parser() .setSigningKey(secretkey) .parseClaimsJws(jwtToken) .getBody(); return JwtAuthenticationToken.of(claims); } catch (ExpiredJwtException | SignatureException e) { throw new BadCredentialsException(e.getMessage(), e); } catch (UnsupportedJwtException | MalformedJwtException e) { throw new AuthenticationServiceException(e.getMessage(), e); } catch (IllegalArgumentException e) { throw new InternalAuthenticationServiceException(e.getMessage(), e); } }