public static boolean Verify(String jwt, String type) throws Exception { try{ Claims claims = Jwts.parser() .setSigningKey(DatatypeConverter.parseBase64Binary(Parameters.TOKENKEY)) .parseClaimsJws(jwt).getBody(); //verifica se o issuer é igual ao type return claims.getIssuer().equals(type); } catch (ExpiredJwtException | MalformedJwtException | SignatureException | UnsupportedJwtException | IllegalArgumentException e) { System.out.println(e.getMessage()); return false; } }
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); } }
@Override public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException { final HttpServletRequest request = (HttpServletRequest) req; final String authHeader = request.getHeader("Authorization"); if (authHeader == null || !authHeader.startsWith("Bearer ")) { throw new ServletException("Missing or invalid Authorization header."); } final String token = authHeader.substring(7); // The part after "Bearer " try { final Claims claims = Jwts.parser().setSigningKey("secretkey") .parseClaimsJws(token).getBody(); request.setAttribute("claims", claims); } catch (final SignatureException e) { throw new ServletException("Invalid token."); } chain.doFilter(req, res); }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // get http servlet request HttpServletRequest req = (HttpServletRequest)request; // get idToken String idToken = req.getHeader("idtoken"); // validate jwt try { logger.info("attempting rvep jwt validation with idToken: "); logger.info(idToken); Jwts.parser().setSigningKey("secretkey") .parseClaimsJws(idToken); } catch (SignatureException e) { // claims may have been tampered with throw error throw new ServletException("Invalid token."); } // validation success, continue processing chain.doFilter(req, response); }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { log.trace("Processing authentication"); HttpServletRequest httprequest = (HttpServletRequest) request; StringBuffer requestURL = httprequest.getRequestURL(); if (httprequest.getQueryString() != null) { requestURL.append("?").append(httprequest.getQueryString()); } String completeURL = requestURL.toString(); log.debug("Request Addr: {}", completeURL); try { Authentication authentication = tokenAuthenticationService.getAuthentication((HttpServletRequest) request); SecurityContextHolder.getContext().setAuthentication(authentication); } catch (SignatureException e) { log.warn("Wrong signature in token."); SecurityContextHolder.getContext().setAuthentication(null); } filterChain.doFilter(request, response); }
@Test(expected = SignatureException.class) public void testJwtToken_Tampered() throws Exception { HmhbUser user = new HmhbUser(); user.setId(USER_ID); user.setEmail(USER_EMAIL); user.setAdmin(false); PublicConfig publicConfig = new PublicConfig(environment); PrivateConfig privateConfig = new PrivateConfig(environment); /* Train the config. */ when(configService.getPublicConfig()).thenReturn(publicConfig); when(configService.getPrivateConfig()).thenReturn(privateConfig); /* Make the generate call. */ String token = toTest.generateJwtToken(user); /* Train the mocks. */ when(request.getHeader("Authorization")).thenReturn("Bearer " + token + "tampered"); /* Make the validate call. */ toTest.validateAuthentication(request); }
private static Claims getBody(String jwt) { return Jwts.parser() .setSigningKeyResolver(new SigningKeyResolverAdapter() { @Override public Key resolveSigningKey(JwsHeader header, Claims claims) { String subject = claims.getSubject(); if (subject == null || subject.isEmpty()) throw new MissingClaimException(header, claims, "Subject is not provided in JWT."); if (!userToKeyMap.containsKey(subject)) throw new SignatureException("Signing key is not reqistred for the subject."); return userToKeyMap.get(subject); }}) .parseClaimsJws(jwt) .getBody(); }
@Override public boolean isValid(byte[] data, byte[] signature) { if (key instanceof PublicKey) { Signature sig = createSignatureInstance(); PublicKey publicKey = (PublicKey) key; try { return doVerify(sig, publicKey, data, signature); } catch (Exception e) { String msg = "Unable to verify RSA signature using configured PublicKey. " + e.getMessage(); throw new SignatureException(msg, e); } } else { Assert.notNull(this.SIGNER, "RSA Signer instance cannot be null. This is a bug. Please report it."); byte[] computed = this.SIGNER.sign(data); return Arrays.equals(computed, signature); } }
@Override public boolean isValid(byte[] data, byte[] signature) { Signature sig = createSignatureInstance(); PublicKey publicKey = (PublicKey) key; try { int expectedSize = getSignatureByteArrayLength(alg); /** * * If the expected size is not valid for JOSE, fall back to ASN.1 DER signature. * This fallback is for backwards compatibility ONLY (to support tokens generated by previous versions of jjwt) * and backwards compatibility will possibly be removed in a future version of this library. * * **/ byte[] derSignature = expectedSize != signature.length && signature[0] == 0x30 ? signature : EllipticCurveProvider.transcodeSignatureToDER(signature); return doVerify(sig, publicKey, data, derSignature); } catch (Exception e) { String msg = "Unable to verify Elliptic Curve signature using configured ECPublicKey. " + e.getMessage(); throw new SignatureException(msg, e); } }
/** * Verifies a web token given a username and token * Checks the given username with the token username to verify usage * * @param token JavaScript Web Token * @param username the given username * @return true if token is fine, otherwise false */ public static boolean verify(String token, String username) { Claims claims = null; UserDaoImpl ud = new UserDaoImpl(); User user = null; String cUsername = null; boolean verified = false; if(token == null) { return false; } try { claims = Jwts.parser() .setSigningKey(getSecret()) .parseClaimsJws(token).getBody(); cUsername = claims.getSubject(); user = ud.getUserByUsername(cUsername); if(cUsername == null || user == null || !cUsername.equals(username)) { return false; } verified = true; }catch(SignatureException se) { } return verified; }
/** * Checks if use is an admin * * @param token the JWT given * @return true if admin exists, false otherwise */ public static boolean isAdmin(String token) { Claims claims = null; UserDaoImpl ud = new UserDaoImpl(); User user = null; String cUsername = null; boolean verified = false; if(token == null) { return false; } try { claims = Jwts.parser() .setSigningKey(getSecret()) .parseClaimsJws(token).getBody(); cUsername = claims.getSubject(); user = ud.getUserByUsername(cUsername); if(cUsername == null || user == null || user.getRoleFlag() != 2) { return false; } verified = true; }catch(SignatureException se) { se.printStackTrace(); } return verified; }
public boolean validateToken(String authToken) { try { Jwts.parser().setSigningKey(secretKey).parseClaimsJws(authToken); return true; } catch (SignatureException e) { log.info("Invalid JWT signature: " + e.getMessage()); return false; } }
private Jws<Claims> parseToken(final String token) { if (token != null) { try { return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token); } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException e) { return null; } } return null; }
/** * Parses and validates JWT Token signature. * * @throws BadCredentialsException * @throws JwtExpiredTokenException * */ public Jws<Claims> parseClaims(String signingKey) { try { return Jwts.parser().setSigningKey(signingKey).parseClaimsJws(this.token); } catch (UnsupportedJwtException | MalformedJwtException | IllegalArgumentException | SignatureException ex) { logger.error("Invalid JWT Token", ex); throw new BadCredentialsException("Invalid JWT token: ", ex); } catch (ExpiredJwtException expiredEx) { logger.info("JWT Token is expired", expiredEx); throw new JwtExpiredTokenException(this, "JWT Token expired", expiredEx); } }
public boolean validateToken(String authToken) { try { Jwts.parser().setSigningKey(secretKey).parseClaimsJws(authToken); return true; } catch (SignatureException e) { LOGGER.log(Level.INFO, "Invalid JWT signature: {0}", e.getMessage()); return false; } }
@Override public Authentication authenticate(Authentication authentication) { log.debug("Authenticating: {}", authentication); try { final String token = authentication.getCredentials().toString(); final Claims claims = jwtParser.parseClaimsJws(token).getBody(); checkClaims(claims); return new JwtToken(token, claims); } catch (ExpiredJwtException | MalformedJwtException | PrematureJwtException | SignatureException | UnsupportedJwtException e) { log.warn("{}", e); throw new BadCredentialsException(e.getMessage(), e); } }
@Test public void testAuthenticateSignatureException() throws Exception { final String token = "token"; doReturn(token).when(authentication).getCredentials(); doThrow(new SignatureException(null)).when(jwtParser).parseClaimsJws(anyString()); exception.expect(BadCredentialsException.class); exception.expectCause(is(instanceOf(SignatureException.class))); jwtAuthenticationProvider.authenticate(authentication); }
private String getUsernameFromToken(String authToken) { String username = null; try { username = jwtTokenService.getUsernameFromToken(authToken); } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException e) { log.error("getUsernameFromToken error, token was malformed: {}", authToken, e); } return username; }
private Optional<Jws<Claims>> parseToken(final String token) { Optional<Jws<Claims>> result = Optional.empty(); if (Objects.nonNull(token)) { try { result = Optional.ofNullable(Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token)); } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException e) { log.warn(e.getMessage()); } } return result; }
public Map<String, Object> getTokenValue(String data) { if (null == data) { return null; } try { final Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(data).getBody(); final Map<String, Object> params = new HashMap<String, Object>(); for (Entry<String, Object> entry : claims.entrySet()) { params.put(entry.getKey(), entry.getValue()); } return params; } catch (SignatureException e) { return null; } }
public static void main (String [] args) { Map<String,Object> claims = new HashMap<String, Object>(); claims.put("id",1); claims.put("name","zeven"); claims.put("role","admin"); String s = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, key).compact(); System.out.println(s); Claims result; try { result = Jwts.parser().setSigningKey(key).parseClaimsJws(s).getBody(); System.out.println(result.get("id")+"|"+result.get("name")+"|"+result.get("role")); } catch (SignatureException e){ System.out.println("401 No Authentication"); } }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION); if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) { throw new NotAuthorizedException("Authorization header must be provided"); } String token = authorizationHeader.substring("Bearer".length()).trim(); try { Role userRole = Role.valueOf(TokenServices.validateToken(token)); List<Role> classRoles = extractRoles(resourceInfo.getResourceClass()); List<Role> methodRoles = extractRoles(resourceInfo.getResourceMethod()); if (methodRoles.size() > 0) { if (!methodRoles.contains(userRole)) { requestContext.abortWith(Response.status(Response.Status.FORBIDDEN).build()); } } if (classRoles.size() > 0) { if (!classRoles.contains(userRole)) { requestContext.abortWith(Response.status(Response.Status.FORBIDDEN).build()); } } } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException e) { requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build()); } }
public static String validateToken(String token)throws ExpiredJwtException, UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException { Claims claims = Jwts.parser().setSigningKey(signingKey).parseClaimsJws(token).getBody(); String role = null; role = claims.get("role").toString(); Jwts.parser() .requireSubject(claims.getSubject()) .setSigningKey(signingKey) .parseClaimsJws(token); return role; }
@Override public InstanceConfirmation postRefreshConfirmation(ResourceContext context, InstanceConfirmation confirmation) { System.out.println("Processing postRefreshConfirmation..."); System.out.println(JSON.string(confirmation)); // our attestation data is jws so we're going to validate // the signature first to make sure that it was signed by us Jws<Claims> claims = null; try { claims = Jwts.parser().setSigningKey(providerKey) .parseClaimsJws(confirmation.getAttestationData()); } catch (SignatureException e) { throw new ResourceException(ResourceException.UNAUTHORIZED); } // we're going to verify that issuer specified in jwt // is indeed ourselves final String provider = claims.getBody().getIssuer(); if (!instanceProvider.equals(provider)) { throw new ResourceException(ResourceException.BAD_REQUEST, "Unknown provider: " + provider); } // we can do other validation possibly - maybe checking // with our manager service that the given instance // was indeed booted for the given domain and service // and it is still running return confirmation; }
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (isExclude(request)) { filterChain.doFilter(request, response); return; } String authorizationHeader = request.getHeader(SessionAndTokenConstants.AUTHORIZATION_HEADER); if (StringUtils.isEmpty(authorizationHeader) || !authorizationHeader.startsWith(BEARER)) { logger.warn("did not find token in header,request:{},ip:{}", request.getRequestURL(), IpUtils.getRemoteIP(request)); convertMsgToJson(response, TokenProvider.DEFAULT_INVALID_JWT_MSG); return; } // The part after "Bearer " final String token = authorizationHeader.substring(7); try { final Claims claims = tokenProvider.getClaimsFromToken(token); tokenProvider.verifyToken(claims); Integer userId = tokenProvider.getUserIdByClaims(claims); request.setAttribute(SessionAndTokenConstants.SESSION_USER_ID, userId); request.setAttribute(SessionAndTokenConstants.TOKEN_CLAIMS, claims); filterChain.doFilter(request, response); } catch (SignatureException exception) { logger.warn("JWT signature does not match locally computed signature,token:{}", token); convertMsgToJson(response, TokenProvider.TOKEN_INVALID_SIGNATURE); } catch (final Exception e) { logger.warn("Could not get claims,invalid token,IP:{},Cause:{}", IpUtils.getRemoteIP(request), e.getMessage()); convertMsgToJson(response, TokenProvider.DEFAULT_EXPIRE_TOKEN_MSG); } }
private Map<String, Object> validateJwt(String token, ApiRequest request, JWTPolicyBean config) throws ExpiredJwtException, PrematureJwtException, MalformedJwtException, SignatureException, InvalidClaimException { JwtParser parser = Jwts.parser() .setSigningKey(config.getSigningKey()) .setAllowedClockSkewSeconds(config.getAllowedClockSkew()); // Set all claims config.getRequiredClaims().stream() // TODO add type variable to allow dates, etc .forEach(requiredClaim -> parser.require(requiredClaim.getClaimName(), requiredClaim.getClaimValue())); return parser.parse(token, new ConfigCheckingJwtHandler(config)); }
@Test(expectedExceptions=SignatureException.class) public void testJwtEncodeAndDecodeWithBadKey() { DawgJwtEncoder helper = new DawgJwtEncoder("14C549805A5911368929D139C5C6282E66CE017F8E861C4EAC4D2975269BEA6F"); DawgCreds dawgJwt = new DawgCreds("kpears201", "pw", Sets.newHashSet("admin", "house"), Sets.newHashSet("id1")); String jwt = helper.createUserJWT(dawgJwt); helper = new DawgJwtEncoder("14C549805A5911368929D139C5C6282E66CE017F8E861C4EAC4D2975269BEA60"); helper.decodeJwt(jwt); }
boolean validateToken(String authToken) { try { Jwts.parser().setSigningKey(secretKey).parseClaimsJws(authToken); return true; } catch (SignatureException e) { log.info("Invalid JWT signature: " + e.getMessage()); return false; } }
@Test public void testJwt() throws NoSuchAlgorithmException, InvalidKeySpecException, IOException, ExpiredJwtException, UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException, CertificateException { Claims testClaims = Jwts.claims(); testClaims.put("aud", "test"); String newJwt = Jwts.builder().setHeaderParam("kid", "test").setClaims(testClaims) .signWith(SignatureAlgorithm.RS256, getKey()).compact(); assertNotNull("could not build jwt using test certificate",newJwt); Jws<Claims> jwt = Jwts.parser().setSigningKey(getCertificate().getPublicKey()).parseClaimsJws(newJwt); assertNotNull("could not decode jwt using test certificate",jwt); }
/** * Get the {@link Ticket} corresponding to the given token. * * @param token * @return null if not found */ public Ticket findByToken(@NotNull String token) { try { Claims claims = Jwts.parser().setSigningKey(configurationService.getConfiguration().getSecretKey().getBytes()) .parseClaimsJws(token).getBody(); return ticketRepository.findOne(claims.getId()); } catch(SignatureException e) { return null; } }
/** * Validate Json web token: issuer, jwt ID and signature verification. * * @param token * @param application Application name requesting validation */ public void validateAccessToken(@NotNull String token, @NotNull String application) { try { Claims claims = Jwts.parser().setSigningKey(configurationService.getConfiguration().getSecretKey().getBytes()) .parseClaimsJws(token).getBody(); if(!getIssuerID().equals(claims.getIssuer())) throw new InvalidTokenException("Token issuer is not valid"); if(!claims.getAudience().contains(application)) { throw new InvalidTokenException("Token is not for '" + application + "'"); } } catch(SignatureException e) { throw new InvalidTokenException("Token signature is not valid"); } }
protected void setParameter(Signature sig, PSSParameterSpec spec) { try { doSetParameter(sig, spec); } catch (InvalidAlgorithmParameterException e) { String msg = "Unsupported RSASSA-PSS parameter '" + spec + "': " + e.getMessage(); throw new SignatureException(msg, e); } }
protected byte[] doSign(byte[] data) throws InvalidKeyException, java.security.SignatureException { PrivateKey privateKey = (PrivateKey)key; Signature sig = createSignatureInstance(); sig.initSign(privateKey); sig.update(data); return sig.sign(); }