io.jsonwebtoken.MalformedJwtException Java Examples

The following examples show how to use io.jsonwebtoken.MalformedJwtException. 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: BaseJwtClientService.java    From devicehive-java-server with Apache License 2.0 6 votes vote down vote up
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 #3
Source File: JwtClientServiceTest.java    From devicehive-java-server with Apache License 2.0 6 votes vote down vote up
@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 #4
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 #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: 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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
Source File: DefaultJwtParser.java    From jjwt with 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 #15
Source File: JwtTokenVerifier.java    From james-project with 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 #16
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 #17
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 #18
Source File: JwtAuthenticatorTest.java    From trellis with 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 #19
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 #20
Source File: AbstractJWTFilter.java    From ambari-logsearch with 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 #21
Source File: DefaultJwtParser.java    From lams with 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 #22
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 #23
Source File: JsonWebTokenAuthenticatorTest.java    From jobson with 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 #24
Source File: CommonUtils.java    From jsets-shiro-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
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 #25
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 #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: 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 #28
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 #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: 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);
}