io.jsonwebtoken.SignatureException Java Examples

The following examples show how to use io.jsonwebtoken.SignatureException. 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: JsonWebTokenUtil.java    From sureness with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param jwt json web token
 * @return 解签实体
 * @throws ExpiredJwtException token过期
 * @throws UnsupportedJwtException 不支持的TOKEN
 * @throws MalformedJwtException 参数格式形变等异常
 * @throws SignatureException 签名异常
 * @throws IllegalArgumentException 非法参数
 */
public static Claims parseJwt(String jwt) throws ExpiredJwtException, UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException {
    return  Jwts.parser()
            .setSigningKey(DatatypeConverter.parseBase64Binary(secretKey))
            .parseClaimsJws(jwt)
            .getBody();

    // 令牌ID -- claims.getId()
    // 客户标识 -- claims.getSubject()
    // 客户标识
    // 签发者 -- claims.getIssuer()
    // 签发时间 -- claims.getIssuedAt()
    // 接收方 -- claims.getAudience()
    // 访问主张-角色 -- claims.get("roles", String.class)
    // 访问主张-权限 -- claims.get("perms", String.class)
}
 
Example #2
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 #3
Source File: JwtFilter.java    From jwt-angular-spring with MIT License 6 votes vote down vote up
@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);
}
 
Example #4
Source File: JwtFilter.java    From atsea-sample-shop-app with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #5
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 #6
Source File: EllipticCurveSignatureValidator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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);
    }
}
 
Example #7
Source File: RsaSignatureValidator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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);
    }
}
 
Example #8
Source File: JjwtVerifierTest.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@Override
protected void validateToken(String token, RSAPublicKey publicKey, String issuer, int expGracePeriodSecs) throws Exception {
    JwtParser parser = Jwts.parser()
        .setSigningKey(publicKey)
        .requireIssuer(issuer)
        ;
    if(expGracePeriodSecs > 0) {
        parser = parser.setAllowedClockSkewSeconds(expGracePeriodSecs);
    }

    Jwt jwt = parser.parse(token);
    String alg = jwt.getHeader().get("alg").toString();
    if(alg == null || !alg.equals(SignatureAlgorithm.RS256.getValue())) {
        throw new SignatureException("Non-RS256 alg: "+alg);
    }
    Jws<Claims> claims = parser.parseClaimsJws(token);
}
 
Example #9
Source File: PageProvider.java    From NetworkDisk_Storage with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 跳转到分享管理页面数据处理
 *
 * @author: quhailong
 * @date: 2019/9/27
 */
public String shareHandle(Model model) {
    String token = CookieUtils.getCookie("token");
    if (!StringUtils.isEmpty(token)) {
        try {
            if (jedisClusterUtil.isExistKey("LOGOUT:" + token)) {
                return "login";
            } else {
                UserInfoDTO userInfoDTO = tokenAnalysisUtils.tokenAnalysis(token);
                model.addAttribute("name", userInfoDTO.getUserName());
                return "share";
            }
        } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException exception) {
            exception.printStackTrace();
            return "user";
        }
    }
    return "login";
}
 
Example #10
Source File: PageProvider.java    From NetworkDisk_Storage with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 跳转到主页面数据处理
 *
 * @author: quhailong
 * @date: 2019/9/27
 */
public String homeHandle(Model model) {
    String token = CookieUtils.getCookie("token");
    if (!StringUtils.isEmpty(token)) {
        try {
            if (jedisClusterUtil.isExistKey("LOGOUT:" + token)) {
                return "login";
            } else {
                UserInfoDTO userInfoDTO = tokenAnalysisUtils.tokenAnalysis(token);
                model.addAttribute("name", userInfoDTO.getUserName());
                return "index";
            }
        } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException exception) {
            exception.printStackTrace();
            return "user";
        }
    }
    return "login";
}
 
Example #11
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 #12
Source File: JWTAuthenticationFilter.java    From spring-security-jwt-csrf with MIT License 5 votes vote down vote up
@Override
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, final FilterChain filterChain) throws ServletException,
        IOException {
    try {
        Authentication authentication = TokenAuthenticationHelper.getAuthentication(request);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(request, response);
    } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException |
            SignatureException | IllegalArgumentException e) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token expired");
    }
}
 
Example #13
Source File: RestAuthTokenInterceptor.java    From jeecg with Apache License 2.0 5 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
	String requestPath = request.getRequestURI().substring(request.getContextPath().length());
	if(requestPath.indexOf("/rest/")==-1 || excludeUrls.contains(requestPath) ||moHuContain(excludeContainUrls, requestPath)){
		return true;
	}
	
	//从header中得到token
	String authHeader = request.getHeader(JwtConstants.AUTHORIZATION);
	if (authHeader == null) {
           throw new ServletException("Missing or invalid X-AUTH-TOKEN header.");
       }
	// 验证token
	Claims claims = null;
	try {
	    claims = Jwts.parser().setSigningKey(JwtConstants.JWT_SECRET).parseClaimsJws(authHeader).getBody();
	}catch (final SignatureException e) {
		throw new ServletException("Invalid token.");
	}
	
	Object username = claims.getId();
	if (oConvertUtils.isEmpty(username)) {
           throw new ServletException("Invalid X-AUTH-TOKEN Subject no exist username.");
       }
	TokenModel model = manager.getToken(authHeader,username.toString());
	if (manager.checkToken(model)) {
		//如果token验证成功,将对象传递给下一个请求
           request.setAttribute(JwtConstants.CURRENT_TOKEN_CLAIMS, claims);
		//如果token验证成功,将token对应的用户id存在request中,便于之后注入
		request.setAttribute(JwtConstants.CURRENT_USER_NAME, model.getUsername());
		return true;
	} else {
		// 如果验证token失败,则返回401错误
		response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
		return false;
	}
}
 
Example #14
Source File: ApigeeSSO2ProviderIT.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@Test
public void testBadSignature() throws Exception {

    // create old keypair
    KeyPair kp = RsaProvider.generateKeyPair(1024);
    PublicKey publicKey = kp.getPublic();
    PrivateKey privateKey = kp.getPrivate();

    // create new keypair
    KeyPair kpNew = RsaProvider.generateKeyPair(1024);
    PrivateKey privateKeyNew = kpNew.getPrivate();

    // create mock provider with old public key
    ApigeeSSO2Provider provider = new MockApigeeSSO2ProviderNewKey( publicKey, publicKey );
    provider.setManagement( setup.getMgmtSvc() );

    // create user, claims and a token for those things. Sign with new public key
    User user = createUser();
    long exp = System.currentTimeMillis() + 10000;
    Map<String, Object> claims = createClaims( user.getUsername(), user.getEmail(), exp );
    String token = Jwts.builder().setClaims(claims).signWith( SignatureAlgorithm.RS256, privateKeyNew).compact();

    // test that signature exception thrown
    try {
        provider.validateAndReturnTokenInfo( token, 86400L );
        Assert.fail("Should have failed due to bad signature");

    } catch ( BadTokenException e ) {
        Assert.assertTrue( e.getCause() instanceof SignatureException );
    }

}
 
Example #15
Source File: BaseController.java    From tutorials with MIT License 5 votes vote down vote up
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler({ SignatureException.class, MalformedJwtException.class, JwtException.class })
public JwtResponse exception(Exception e) {
    JwtResponse response = new JwtResponse();
    response.setStatus(JwtResponse.Status.ERROR);
    response.setMessage(e.getMessage());
    response.setExceptionType(e.getClass()
        .getName());

    return response;
}
 
Example #16
Source File: JwtAuthenticationFilter.java    From SpringSecurity-JWT-Vue-Deom with MIT License 5 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
    try {
        Authentication authentication = TokenAuthenticationHelper.getAuthentication(httpServletRequest);

        // 对用 token 获取到的用户进行校验
        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException |
            SignatureException | IllegalArgumentException e) {
        httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token expired,登陆已过期");
    }
}
 
Example #17
Source File: JwtGeneratorTest.java    From cloud-iot-core-androidthings with Apache License 2.0 5 votes vote down vote up
/**
 * Make sure Jwt created is formatted according to the Google Cloud IoT Core<a
 * href="https://cloud.google.com/iot/docs/how-tos/credentials/jwts#jwt_composition">spec</a>.
 */
@Test
public void testCreateJwtEc() throws JoseException {
    JwtGenerator jwtGenerator =
            new JwtGenerator(EC_KEY_PAIR, JWT_AUDIENCE, TOKEN_LIFETIME, TEST_CLOCK);
    String rawJwt = jwtGenerator.createJwt();

    // Validate JWT
    Jws<Claims> parsedJwt;
    try {
        parsedJwt = Jwts.parser()
                .setSigningKey(EC_KEY_PAIR.getPublic())
                .parseClaimsJws(rawJwt);
    } catch (UnsupportedJwtException | MalformedJwtException | SignatureException e) {
        fail("Error parsing JWT: " + e);
        return;  // Satisfy compiler
    }

    JwsHeader header = parsedJwt.getHeader();
    Claims claims = parsedJwt.getBody();

    assertThat(header.getAlgorithm()).isEqualTo("ES256");
    assertThat(header.getType()).isEqualTo("JWT");
    assertThat(claims.getAudience()).isEqualTo(JWT_AUDIENCE);

    // JWT requires time in seconds from epoch, not millis, so allow issue time within one
    // second.
    assertThat(claims.getIssuedAt().getTime()).isAtLeast(TEST_CLOCK.millis() - 1000);
    assertThat(claims.getIssuedAt().getTime()).isAtMost(TEST_CLOCK.millis() + 1000);

    // Check expiration time within one second of issue time + TOKEN_LIFETIME
    assertThat(claims.getExpiration().getTime())
            .isLessThan(Clock.offset(TEST_CLOCK, TOKEN_LIFETIME.plusSeconds(1)).millis());
    assertThat(claims.getExpiration().getTime())
            .isAtLeast(Clock.offset(TEST_CLOCK, TOKEN_LIFETIME.minusSeconds(1)).millis());
}
 
Example #18
Source File: JWTPolicy.java    From apiman-plugins with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> validateJwt(String token, JWTPolicyBean config)
        throws ExpiredJwtException, PrematureJwtException, MalformedJwtException, SignatureException, InvalidClaimException {

    // check if we have to use jwk(s)
    if (urlValidator.isValid(config.getSigningKeyString())){
        if (provider == null){
            provider = getNewJwksProvider(config.getSigningKeyString());
        }

        Jwk jwk;
        try {
            jwk = provider.get(config.getKid());
            if (config.getSigningKey() == null || !(config.getSigningKey().equals(jwk.getPublicKey()))) {
                config.setSigningKey(jwk.getPublicKey());
            }
        } catch (JwkException e) {
           throw new SignatureException("JWK was not found with kid: " + config.getKid(), e);
        }
    }

    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));
}
 
Example #19
Source File: InstanceProviderHandlerImpl.java    From athenz with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #20
Source File: Auth.java    From zevencourse with GNU General Public License v3.0 5 votes vote down vote up
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");
    }
}
 
Example #21
Source File: RawAccessJwtToken.java    From springboot-security-jwt with MIT License 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example #22
Source File: TokenProvider.java    From gpmr with Apache License 2.0 5 votes vote down vote up
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;
    }
}
 
Example #23
Source File: RawAccessJwtToken.java    From iotplatform with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
  }
}
 
Example #24
Source File: TokenProvider.java    From javaee8-jaxrs-sample with GNU General Public License v3.0 5 votes vote down vote up
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;
    }
}
 
Example #25
Source File: TokenProvider.java    From klask-io with GNU General Public License v3.0 5 votes vote down vote up
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;
    }
}
 
Example #26
Source File: JWTFilter.java    From Java-EE-8-and-Angular with MIT License 5 votes vote down vote up
private String getUserIfValid(String token) {
    Key key = new SecretKeySpec("secret".getBytes(), "DES");
    try {
        Jws<Claims> claims = Jwts.parser().setSigningKey(key)
                .parseClaimsJws(token);
        String scope = claims.getBody().get("scope", String.class);
        System.out.println("scope " + scope);
        return claims.getBody().getSubject();
    } catch (ExpiredJwtException | MalformedJwtException | SignatureException | UnsupportedJwtException | IllegalArgumentException e) {
        //don't trust the JWT!            
        throw new NotAuthorizedException("Invalid JWT");
    }
}
 
Example #27
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 #28
Source File: JWTFilter.java    From Java-EE-8-and-Angular with MIT License 5 votes vote down vote up
private String getUserIfValid(String token) {
    Key key = new SecretKeySpec("secret".getBytes(), "DES");
    try {
        Jws<Claims> claims = Jwts.parser().setSigningKey(key)
                .parseClaimsJws(token);
        String scope = claims.getBody().get("scope", String.class);
        System.out.println("scope " + scope);
        return claims.getBody().getSubject();
    } catch (ExpiredJwtException | MalformedJwtException | SignatureException | UnsupportedJwtException | IllegalArgumentException e) {
        //don't trust the JWT!
        e.printStackTrace();
        throw new NotAuthorizedException("Invalid JWT");
    }
}
 
Example #29
Source File: AbstractVerifierTest.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = {BadJWSException.class, SignatureVerificationException.class,
    InvalidJwtSignatureException.class, SignatureException.class},
    description = "Illustrate validation of signer")
public void testFailSignature() throws Exception {
    HashSet<TokenUtils.InvalidClaims> invalidFields = new HashSet<>();
    invalidFields.add(TokenUtils.InvalidClaims.SIGNER);
    String token = TokenUtils.generateTokenString("/Token1.json", invalidFields);
    RSAPublicKey publicKey = (RSAPublicKey) TokenUtils.readPublicKey("/publicKey.pem");
    int expGracePeriodSecs = 60;
    validateToken(token, publicKey, TEST_ISSUER, expGracePeriodSecs);
}
 
Example #30
Source File: RsaSigner.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 {
    PrivateKey privateKey = (PrivateKey)key;
    Signature sig = createSignatureInstance();
    sig.initSign(privateKey);
    sig.update(data);
    return sig.sign();
}