io.jsonwebtoken.UnsupportedJwtException Java Examples

The following examples show how to use io.jsonwebtoken.UnsupportedJwtException. 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: 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 #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: JwtAuthorizationHeaderFilter.java    From training with MIT License 6 votes vote down vote up
@Override
protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {

	String jwtHeader = request.getHeader(JWT_HEADER_NAME);

	if (jwtHeader == null) {
		return null;
	}

	String encodedJwt = jwtHeader;

	try {
		Claims claims = Jwts.parser()
				.setSigningKey(DatatypeConverter.parseBase64Binary(backendSecret))
				.parseClaimsJws(encodedJwt)
				.getBody();

		AuthnContext authnContext = getAuthnContext(claims);
		log.info("Attempting login with userid={} and level={}", claims.getSubject(), authnContext);
		return new UsernameContextPrincipal(claims.getSubject(), authnContext);
	} catch (UnsupportedJwtException jwtException) {
		throw new PreAuthenticatedCredentialsNotFoundException("Invalid JWT Token", jwtException);
	}
}
 
Example #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
Source File: DefaultJwtParser.java    From jjwt with Apache License 2.0 5 votes vote down vote up
@Override
public Jws<String> parsePlaintextJws(String plaintextJws) {
    try {
        return parse(plaintextJws, new JwtHandlerAdapter<Jws<String>>() {
            @Override
            public Jws<String> onPlaintextJws(Jws<String> jws) {
                return jws;
            }
        });
    } catch (IllegalArgumentException iae) {
        throw new UnsupportedJwtException("Signed JWSs are not supported.", iae);
    }
}
 
Example #11
Source File: DefaultJwtParser.java    From jjwt with Apache License 2.0 5 votes vote down vote up
@Override
public Jwt<Header, Claims> parseClaimsJwt(String claimsJwt) {
    try {
        return parse(claimsJwt, new JwtHandlerAdapter<Jwt<Header, Claims>>() {
            @Override
            public Jwt<Header, Claims> onClaimsJwt(Jwt<Header, Claims> jwt) {
                return jwt;
            }
        });
    } catch (IllegalArgumentException iae) {
        throw new UnsupportedJwtException("Signed JWSs are not supported.", iae);
    }
}
 
Example #12
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 #13
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 #14
Source File: JsonWebTokenAuthenticator.java    From presto with Apache License 2.0 5 votes vote down vote up
public Key getKey(SignatureAlgorithm algorithm)
{
    if (algorithm.isHmac()) {
        if (hmacKey == null) {
            throw new UnsupportedJwtException(format("JWT is signed with %s, but no HMAC key is configured", algorithm));
        }
        return new SecretKeySpec(hmacKey, algorithm.getJcaName());
    }

    if (publicKey == null) {
        throw new UnsupportedJwtException(format("JWT is signed with %s, but no key is configured", algorithm));
    }
    return publicKey;
}
 
Example #15
Source File: DefaultJwtParser.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Jws<String> parsePlaintextJws(String plaintextJws) {
    try {
        return parse(plaintextJws, new JwtHandlerAdapter<Jws<String>>() {
            @Override
            public Jws<String> onPlaintextJws(Jws<String> jws) {
                return jws;
            }
        });
    } catch (IllegalArgumentException iae) {
        throw new UnsupportedJwtException("Signed JWSs are not supported.", iae);
    }
}
 
Example #16
Source File: JsonWebTokenAuthenticationService.java    From spring-boot-mongodb-jwt with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #17
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 #18
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 #19
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 #20
Source File: AbstractVerifierTest.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = {JOSEException.class, AlgorithmMismatchException.class, InvalidJwtException.class, UnsupportedJwtException.class},
    description = "Illustrate validation of signature algorithm")
public void testFailSignatureAlgorithm() throws Exception {
    HashSet<TokenUtils.InvalidClaims> invalidFields = new HashSet<>();
    invalidFields.add(TokenUtils.InvalidClaims.ALG);
    String token = TokenUtils.generateTokenString("/Token1.json", invalidFields);
    RSAPublicKey publicKey = (RSAPublicKey) TokenUtils.readPublicKey("/publicKey.pem");
    int expGracePeriodSecs = 60;
    validateToken(token, publicKey, TEST_ISSUER, expGracePeriodSecs);
}
 
Example #21
Source File: DefaultJwtParser.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Jwt<Header, Claims> parseClaimsJwt(String claimsJwt) {
    try {
        return parse(claimsJwt, new JwtHandlerAdapter<Jwt<Header, Claims>>() {
            @Override
            public Jwt<Header, Claims> onClaimsJwt(Jwt<Header, Claims> jwt) {
                return jwt;
            }
        });
    } catch (IllegalArgumentException iae) {
        throw new UnsupportedJwtException("Signed JWSs are not supported.", iae);
    }
}
 
Example #22
Source File: PageProvider.java    From NetworkDisk_Storage with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 查看分享页面数据处理
 *
 * @author: quhailong
 * @date: 2019/9/27
 */
public String sHandle(Model model, String shareId) {
    String token = CookieUtils.getCookie("token");
    if (!StringUtils.isEmpty(token)) {
        try {
            if (jedisClusterUtil.isExistKey("LOGOUT:" + token)) {
                return "login";
            } else {
                UserInfoDTO userInfoDTO = tokenAnalysisUtils.tokenAnalysis(token);
                String getShareUserUrl = "http://localhost:8095/api/share/getshareuser?shareId=" + shareId;
                String resultString = HttpClientUtils.HttpGet(getShareUserUrl);
                RestAPIResult restAPIResult = JSONUtils.parseObject(resultString, RestAPIResult.class);
                Map<String, Object> map = restAPIResult.getRespMap();
                UserInfoDTO shareUserInfoDTO = JSONUtils.parseObject((String) map.get("userinfo"), UserInfoDTO.class);
                if (shareUserInfoDTO == null) {
                    model.addAttribute("name", userInfoDTO.getUserName());
                    return "sError";
                } else if (shareUserInfoDTO.getUserId().equals(userInfoDTO.getUserId())) {
                    model.addAttribute("name", userInfoDTO.getUserName());
                    return "share";
                }
                ShareDTO shareDTO = JSONUtils.parseObject((String) map.get("share"), ShareDTO.class);
                if (shareDTO.getExpiration() != null && shareDTO.getExpiration().getTime() - (new Date().getTime()) < 0) {
                    return "sError";
                }
                model.addAttribute("name", userInfoDTO.getUserName());
                model.addAttribute("shareUser", shareUserInfoDTO.getUserName());
                if (shareDTO.getMultiWhether() == 1) {
                    model.addAttribute("shareName", shareDTO.getTheme() + "等文件");
                } else {
                    model.addAttribute("shareName", shareDTO.getTheme() + "文件");
                }
                String addShareViewCountUrl = "http://localhost:8095/api/share/addshareview";
                AddShareViewCountRequest addShareViewCountRequest = new AddShareViewCountRequest();
                addShareViewCountRequest.setShareId(shareId);
                HttpClientUtils.httpPostWithJSON(addShareViewCountUrl, JSONUtils.toJSONString(addShareViewCountRequest));
                model.addAttribute("shareId", shareDTO.getShareId());
                return "s";
            }
        } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException exception) {
            exception.printStackTrace();
            return "user";
        }
    }
    return "login";
}
 
Example #23
Source File: PolicyFailureFactory.java    From apiman-plugins with Apache License 2.0 4 votes vote down vote up
public PolicyFailure unsupportedJwt(IPolicyContext context, UnsupportedJwtException e) {
    return createAuthenticationPolicyFailure(context, AUTH_JWT_UNSUPPORTED_JWT,
            Messages.getString("JWTPolicy.NoTransportSecurity")); //$NON-NLS-1$
}
 
Example #24
Source File: LTI13Servlet.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
protected SakaiAccessToken getSakaiAccessToken(Key publicKey, HttpServletRequest request, HttpServletResponse response) {
	String authorization = request.getHeader("authorization");

	if (authorization == null || !authorization.startsWith("Bearer")) {
		log.error("Invalid authorization {}", authorization);
		LTI13Util.return400(response, "invalid_authorization");
		return null;
	}

	// https://stackoverflow.com/questions/7899525/how-to-split-a-string-by-space/7899558
	String[] parts = authorization.split("\\s+");
	if (parts.length != 2 || parts[1].length() < 1) {
		log.error("Bad authorization {}", authorization);
		LTI13Util.return400(response, "invalid_authorization");
		return null;
	}

	String jws = parts[1];
	Claims claims;
	try {
		claims = Jwts.parser().setSigningKey(publicKey).parseClaimsJws(jws).getBody();
	} catch (ExpiredJwtException | MalformedJwtException | UnsupportedJwtException
			| io.jsonwebtoken.security.SignatureException | IllegalArgumentException e) {
		log.error("Signature error {}\n{}", e.getMessage(), jws);
		LTI13Util.return400(response, "signature_error");
		return null;
	}

	// Reconstruct the SakaiAccessToken
	// https://www.baeldung.com/jackson-deserialization
	SakaiAccessToken sat;
	try {
		ObjectMapper mapper = new ObjectMapper();
		String jsonResult = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(claims);
		// System.out.println("jsonResult=" + jsonResult);
		sat = new ObjectMapper().readValue(jsonResult, SakaiAccessToken.class);
	} catch (IOException ex) {
		log.error("PARSE ERROR {}\n{}", ex.getMessage(), claims.toString());
		LTI13Util.return400(response, "token_parse_failure", ex.getMessage());
		return null;
	}

	// Validity check the access token
	if (sat.tool_id != null && sat.scope != null && sat.expires != null) {
		// All good
	} else {
		log.error("SakaiAccessToken missing required data {}", sat);
		LTI13Util.return400(response, "Missing required data in access_token");
		return null;
	}

	return sat;
}
 
Example #25
Source File: ImmutableJwtParser.java    From jjwt with Apache License 2.0 4 votes vote down vote up
@Override
public <T> T parse(String jwt, JwtHandler<T> handler) throws ExpiredJwtException, UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException {
    return this.jwtParser.parse(jwt, handler);
}
 
Example #26
Source File: ImmutableJwtParser.java    From jjwt with Apache License 2.0 4 votes vote down vote up
@Override
public Jwt<Header, String> parsePlaintextJwt(String plaintextJwt) throws UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException {
    return this.jwtParser.parsePlaintextJwt(plaintextJwt);
}
 
Example #27
Source File: ImmutableJwtParser.java    From jjwt with Apache License 2.0 4 votes vote down vote up
@Override
public Jwt<Header, Claims> parseClaimsJwt(String claimsJwt) throws ExpiredJwtException, UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException {
    return this.jwtParser.parseClaimsJwt(claimsJwt);
}
 
Example #28
Source File: ImmutableJwtParser.java    From jjwt with Apache License 2.0 4 votes vote down vote up
@Override
public Jws<String> parsePlaintextJws(String plaintextJws) throws UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException {
    return this.jwtParser.parsePlaintextJws(plaintextJws);
}
 
Example #29
Source File: ImmutableJwtParser.java    From jjwt with Apache License 2.0 4 votes vote down vote up
@Override
public Jws<Claims> parseClaimsJws(String claimsJws) throws ExpiredJwtException, UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException {
    return this.jwtParser.parseClaimsJws(claimsJws);
}
 
Example #30
Source File: ForwardActivityFilter.java    From rh-che with Eclipse Public License 2.0 4 votes vote down vote up
private String extractUserId(HttpServletRequest httpRequest, String workspaceId) {
  // First search in the session fro activity notification coming from the client

  final HttpSession session = httpRequest.getSession();

  Subject subject = (Subject) session.getAttribute("che_subject");
  if (subject != null) {
    String userId = subject.getUserId();
    if (userId != null) {
      return userId;
    }
  }

  // Then search in the machine token for activity notification coming from the agents

  final String token = tokenExtractor.getToken(httpRequest);

  if (isNullOrEmpty(token)) {
    return null;
  }

  // check token signature and verify is this token machine or not
  try {
    final Jws<Claims> jwt =
        Jwts.parser()
            .setSigningKey(keyManager.getOrCreateKeyPair(workspaceId).getPublic())
            .parseClaimsJws(token);
    final Claims claims = jwt.getBody();

    if (MACHINE_TOKEN_KIND.equals(jwt.getHeader().get("kind"))) {
      return claims.get(USER_ID_CLAIM, String.class);
    }
  } catch (UnsupportedJwtException
      | MalformedJwtException
      | SignatureException
      | SignatureKeyManagerException
      | ExpiredJwtException
      | IllegalArgumentException ex) {
    LOG.warn("Could not get a user Id from a machine token", ex);
  }
  return null;
}