类io.jsonwebtoken.MalformedJwtException源码实例Demo

下面列出了怎么用io.jsonwebtoken.MalformedJwtException的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: sureness   文件: JsonWebTokenUtil.java
/**
 *
 * @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)
}
 
源代码2 项目: localization_nifi   文件: JwtService.java
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);
    }
}
 
源代码3 项目: NetworkDisk_Storage   文件: PageProvider.java
/**
 * 跳转到主页面数据处理
 *
 * @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";
}
 
源代码4 项目: NetworkDisk_Storage   文件: PageProvider.java
/**
 * 跳转到分享管理页面数据处理
 *
 * @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";
}
 
源代码5 项目: nifi-registry   文件: JwtService.java
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);
    }
}
 
源代码6 项目: nifi   文件: JwtService.java
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);
    }
}
 
@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);
}
 
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();
    }
}
 
@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,登陆已过期");
    }
}
 
/**
 * 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());
}
 
@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");
    }
}
 
源代码12 项目: ambari-logsearch   文件: AbstractJWTFilter.java
@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);
  }
}
 
源代码13 项目: Java-EE-8-and-Angular   文件: JWTFilter.java
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");
    }
}
 
源代码14 项目: Java-EE-8-and-Angular   文件: JWTFilter.java
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");
    }
}
 
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);
	}
}
 
源代码16 项目: jobson   文件: JsonWebTokenAuthenticatorTest.java
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.");
    }
}
 
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;
}
 
源代码18 项目: lams   文件: DefaultJwtParser.java
@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);
    }
}
 
源代码19 项目: iotplatform   文件: RawAccessJwtToken.java
/**
 * 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);
  }
}
 
源代码20 项目: trellis   文件: JwtAuthenticatorTest.java
@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!");
}
 
/**
 * 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);
    }
}
 
源代码22 项目: apiman-plugins   文件: JWTPolicy.java
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));
}
 
源代码23 项目: james-project   文件: JwtTokenVerifier.java
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;
    }
}
 
源代码24 项目: jjwt   文件: DefaultJwtParser.java
@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);
    }
}
 
源代码25 项目: tutorials   文件: BaseController.java
@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;
}
 
源代码26 项目: NetworkDisk_Storage   文件: PageProvider.java
/**
 * 查看分享页面数据处理
 *
 * @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";
}
 
@ExceptionHandler(value = {MalformedJwtException.class})
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public Result handle(MalformedJwtException ex) {
    log.error("MalformedJwtException:{}", ex.getMessage());
    return Result.fail(SystemErrorType.INVALID_TOKEN);
}
 
源代码28 项目: rh-che   文件: ForwardActivityFilter.java
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;
}
 
源代码29 项目: apiman-plugins   文件: PolicyFailureFactory.java
public PolicyFailure jwtMalformed(IPolicyContext context, MalformedJwtException e) {
    return createAuthenticationPolicyFailure(context, AUTH_JWT_MALFORMED,
            e.getLocalizedMessage());
}
 
源代码30 项目: sakai   文件: LTI13Servlet.java
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;
}
 
 类所在包