Java Code Examples for io.jsonwebtoken.MalformedJwtException

The following examples show how to use io.jsonwebtoken.MalformedJwtException. These examples are extracted from open source projects. 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 Project: sureness   Source File: JsonWebTokenUtil.java    License: 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 Project: localization_nifi   Source File: JwtService.java    License: 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
/**
 * 跳转到主页面数据处理
 *
 * @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 4
/**
 * 跳转到分享管理页面数据处理
 *
 * @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 Project: nifi-registry   Source File: JwtService.java    License: 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 Project: nifi   Source File: JwtService.java    License: 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
@Test(expected = MalformedJwtException.class)
public void should_throw_MalformedJwtException_whet_pass_token_without_expiration_and_type() throws Exception {
    // Create payload
    Long userId = RandomUtils.nextLong(10, 1000);
    Set<Integer> actions = new HashSet<>();
    actions.add(0);
    Set<String> networkIds = new HashSet<>();
    networkIds.add("string");
    Set<String> deviceTypeIds = new HashSet<>();
    deviceTypeIds.add("string");
    Set<String> deviceIds = new HashSet<>();
    deviceIds.add("string");
    JwtUserPayload.JwtUserPayloadBuilder jwtUserPayloadBuilder = new JwtUserPayload.JwtUserPayloadBuilder();
    JwtUserPayload payload = jwtUserPayloadBuilder.withPublicClaims(userId, actions, networkIds, deviceTypeIds).buildPayload();

    // Generate key without expiration date and token type
    Map<String, Object> jwtMap = new HashMap<>();
    jwtMap.put(JwtUserPayload.JWT_CLAIM_KEY, payload);
    Claims claims = Jwts.claims(jwtMap);
    String malformedToken = Jwts.builder()
            .setClaims(claims)
            .signWith(SignatureAlgorithm.HS256, jwtSecretService.getJwtSecret())
            .compact();
    jwtClientService.getUserPayload(malformedToken);
}
 
Example 8
private JwtPayload getJwtPayload(JwtPayload.JwtPayloadBuilder jwtPayloadBuilder, LinkedHashMap<String, Object> payloadMap) {
    Optional<Long> expiration = Optional.ofNullable((Long)payloadMap.get(EXPIRATION));
    Optional<Integer> tokenType = Optional.ofNullable((Integer) payloadMap.get(TOKEN_TYPE));

    if (!tokenType.isPresent() && !expiration.isPresent()) {
        throw new MalformedJwtException("Token type and expiration date should be provided in the token");
    } else {
        if (tokenType.isPresent())
            jwtPayloadBuilder.withTokenType(tokenType.get());
        else
            throw new MalformedJwtException("Token type should be provided in the token");
        if (expiration.isPresent())
            jwtPayloadBuilder.withExpirationDate(new Date(expiration.get()));
        else
            throw new MalformedJwtException("Expiration date should be provided in the token");
        return jwtPayloadBuilder.buildPayload();
    }
}
 
Example 9
@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
/**
 * 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 11
Source Project: spring-security-jwt-csrf   Source File: JWTAuthenticationFilter.java    License: 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 12
Source Project: ambari-logsearch   Source File: AbstractJWTFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
  if (StringUtils.isEmpty(getProvidedUrl())) {
    throw new BadCredentialsException("Authentication provider URL must not be null or empty.");
  }
  if (StringUtils.isEmpty(getPublicKey())) {
    throw new BadCredentialsException("Public key for signature validation must be provisioned.");
  }

  try {
    Claims claims = Jwts
      .parser()
      .setSigningKey(parseRSAPublicKey(getPublicKey()))
      .parseClaimsJws(getJWTFromCookie(request))
      .getBody();
    String userName  = claims.getSubject();
    logger.info("USERNAME: " + userName);
    logger.info("URL = " + request.getRequestURL());
    if (StringUtils.isNotEmpty(claims.getAudience()) && !getAudiences().contains(claims.getAudience())) {
      throw new IllegalArgumentException(String.format("Audience validation failed. (Not found: %s)", claims.getAudience()));
    }
    Authentication authentication = new JWTAuthenticationToken(userName, getPublicKey(), getAuthorities(userName));
    authentication.setAuthenticated(true);
    SecurityContextHolder.getContext().setAuthentication(authentication);
    return authentication;
  } catch (ExpiredJwtException | MalformedJwtException | SignatureException | IllegalArgumentException e) {
    logger.info("URL = " + request.getRequestURL());
    logger.warn("Error during JWT authentication: {}", e.getMessage());
    throw new BadCredentialsException(e.getMessage(), e);
  }
}
 
Example 13
Source Project: Java-EE-8-and-Angular   Source File: JWTFilter.java    License: 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 14
Source Project: Java-EE-8-and-Angular   Source File: JWTFilter.java    License: 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 15
public static <T> T readJSON(String val,Class<T> clazz) {
	try {
		return MAPPER.readValue(val, clazz);
	} catch (Exception e) {
		throw new MalformedJwtException("Unable to read JSON value: " + val, e);
	}
}
 
Example 16
Source Project: jobson   Source File: JsonWebTokenAuthenticatorTest.java    License: Apache License 2.0 5 votes vote down vote up
private static void assertIsValidJWT(Key secretKey, String jwtString) {
    try {
        Jwts.parser().setSigningKey(secretKey).parse(jwtString);
    } catch (MalformedJwtException ex) {
        Assert.fail(jwtString + ": not a valid JWT.");
    }
}
 
Example 17
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 18
Source Project: lams   Source File: DefaultJwtParser.java    License: GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected Map<String, Object> readValue(String val) {
    try {
        return objectMapper.readValue(val, Map.class);
    } catch (IOException e) {
        throw new MalformedJwtException("Unable to read JSON value: " + val, e);
    }
}
 
Example 19
Source Project: iotplatform   Source File: RawAccessJwtToken.java    License: 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 20
Source Project: trellis   Source File: JwtAuthenticatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testGarbledToken() {
    final String key = "thj983z1fiqAiaV7Nv4nWpjaDi6eVTd7jOGxbs92mp8=";
    final String token = "blahblah";

    final Authenticator authenticator = new JwtAuthenticator(hmacShaKeyFor(Base64.getDecoder().decode(key)));

    assertThrows(MalformedJwtException.class, () -> authenticator.authenticate(token), "Parsed bad JWT!");
}
 
Example 21
Source Project: springboot-security-jwt   Source File: RawAccessJwtToken.java    License: 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 Project: apiman-plugins   Source File: JWTPolicy.java    License: 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 23
Source Project: james-project   Source File: JwtTokenVerifier.java    License: 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 24
Source Project: jjwt   Source File: DefaultJwtParser.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected Map<String, ?> readValue(String val) {
    try {
        byte[] bytes = val.getBytes(Strings.UTF_8);
        return deserializer.deserialize(bytes);
    } catch (DeserializationException e) {
        throw new MalformedJwtException("Unable to read JSON value: " + val, e);
    }
}
 
Example 25
Source Project: tutorials   Source File: BaseController.java    License: 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 26
/**
 * 查看分享页面数据处理
 *
 * @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 27
Source Project: SpringCloud   Source File: GateWayExceptionHandlerAdvice.java    License: Apache License 2.0 4 votes vote down vote up
@ExceptionHandler(value = {MalformedJwtException.class})
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public Result handle(MalformedJwtException ex) {
    log.error("MalformedJwtException:{}", ex.getMessage());
    return Result.fail(SystemErrorType.INVALID_TOKEN);
}
 
Example 28
Source Project: rh-che   Source File: ForwardActivityFilter.java    License: 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;
}
 
Example 29
Source Project: apiman-plugins   Source File: PolicyFailureFactory.java    License: Apache License 2.0 4 votes vote down vote up
public PolicyFailure jwtMalformed(IPolicyContext context, MalformedJwtException e) {
    return createAuthenticationPolicyFailure(context, AUTH_JWT_MALFORMED,
            e.getLocalizedMessage());
}
 
Example 30
Source Project: sakai   Source File: LTI13Servlet.java    License: 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;
}