io.jsonwebtoken.Claims Java Examples

The following examples show how to use io.jsonwebtoken.Claims. 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: AuthenticationService.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Parses the JWT token and return a {@link QueryResponse} object containing the domain, user id, type (Zowe / z/OSMF),
 * date of creation and date of expiration
 *
 * @param jwtToken the JWT token
 * @return the query response
 */
public QueryResponse parseJwtToken(String jwtToken) {
    /*
     * Removes signature, because of z/OSMF we don't have key to verify certificate and
     * we just need to read claim. Verification is realized via REST call to z/OSMF.
     * JWT library doesn't parse signed key without verification.
     */
    final String withoutSign = removeSign(jwtToken);

    // parse to claims and construct QueryResponse
    try {
        Claims claims = Jwts.parser()
            .parseClaimsJwt(withoutSign)
            .getBody();
        return new QueryResponse(
            claims.get(DOMAIN_CLAIM_NAME, String.class),
            claims.getSubject(),
            claims.getIssuedAt(),
            claims.getExpiration(),
            QueryResponse.Source.valueByIssuer(claims.getIssuer())
        );
    } catch (RuntimeException exception) {
        throw handleJwtParserException(exception);
    }
}
 
Example #2
Source File: JwtUtils.java    From mini-platform with MIT License 6 votes vote down vote up
/**
 * 使用HS256签名算法和生成的signingKey最终的Token,claims中是有效载荷
 *
 * @param userName     = sub JWT面向的用户 (User)
 * @param clientId   = aud 接受JWT的一方 (Client)
 * @param expiration = exp  过期时间
 * @param issuedAt   = iat  签发时间
 * @return
 */
public static String createJavaWebToken(Long userId, String userName, String clientId, String scope,
                                        Date expiration, Date issuedAt) {

    Claims claims = Jwts.claims();
    claims.put(USER_ID_KEY, userId);
    claims.put(USER_NAME_KEY, userName);
    claims.put(CLIENT_ID_KEY, clientId);
    claims.put(SCOPE_KEY, scope);

    String token = Jwts.builder()
            .setClaims(claims)
            //JWT的签发者
            //.setIssuer("oauth")
            //.setSubject(userId)
            //.setAudience(clientId)
            .setExpiration(expiration)
            .setIssuedAt(issuedAt)
            .signWith(SignatureAlgorithm.HS256, getKeyInstance())
            .compact();
    return token;
}
 
Example #3
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 #4
Source File: JwtService.java    From hauth-java with MIT License 6 votes vote down vote up
public static Authentication getAuthentication(HttpServletRequest request) {

        // 从Header中拿到token
        String token = request.getHeader(HEADER_STRING);
        if (token == null) {
            token = getTokenFromCookis(request);
        }

        if (token != null && !token.isEmpty()) {
            // 解析 Token
            Claims claims = Jwts.parser().setSigningKey(SECRET)
                    .parseClaimsJws(token).getBody();

            // 获取用户名
            String user = claims.get("UserId").toString();

            // 获取权限(角色)
            List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) claims.get("authorities"));

            // 返回验证令牌
            return user != null ? new UsernamePasswordAuthenticationToken(user, null, authorities) : null;
        }
        return null;
    }
 
Example #5
Source File: JwksAuthenticator.java    From trellis with Apache License 2.0 6 votes vote down vote up
@Override
public Claims parse(final String token) {
    return Jwts.parserBuilder().setSigningKeyResolver(new SigningKeyResolverAdapter() {
        @Override
        public Key resolveSigningKey(final JwsHeader header, final Claims claims) {
            final String keyid = header.getKeyId();
            if (keyid == null) {
                throw new JwtException("Missing Key ID (kid) header field");
            }
            if (keys.containsKey(keyid)) {
                return keys.get(keyid);
            }
            throw new SecurityException("Could not locate key: " + keyid);
        }
    }).build().parseClaimsJws(token).getBody();
}
 
Example #6
Source File: JwtService.java    From hauth-java with MIT License 6 votes vote down vote up
public static RequestUserDTO getConnUser(HttpServletRequest request) {
    String token = request.getHeader(HEADER_STRING);
    if (token == null) {
        token = getTokenFromCookis(request);
    }
    if (token != null) {
        // 解析 Token
        Claims claims = Jwts.parser().setSigningKey(SECRET)
                .parseClaimsJws(token).getBody();

        return new RequestUserDTO(
                claims.get("DomainId", String.class),
                claims.get("UserId", String.class),
                claims.get("OrgUnitId", String.class));
    }
    return new RequestUserDTO();
}
 
Example #7
Source File: JwtUtils.java    From common-project with Apache License 2.0 6 votes vote down vote up
/**
 * 解析token
 *
 * @param token
 * @return
 * @throws Exception
 */
public static AuthTokenDetails parseToken(String token) throws Exception {
    Claims claims = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
    String userId = claims.getSubject();
    String appId = (String) claims.get(APP_ID_FIELD);
    String organizationId = (String) claims.get(ORGANIZATION_ID_FIELD);
    String roleId = (String) claims.get(ROLE_ID_FIELD);
    String roleType = (String) claims.get(ROLE_TYPE_FIELD);
    String language = (String) claims.get(LANGUAGE_FIELD);
    Date expirationDate = claims.getExpiration();

    AuthTokenDetails authTokenDetails = new AuthTokenDetails();
    authTokenDetails.setUserId(Long.valueOf(userId));
    authTokenDetails.setAppId(appId);
    authTokenDetails.setOrganizationId(Long.valueOf(organizationId));
    authTokenDetails.setRoleId(roleId == null ? null : Long.valueOf(roleId));
    authTokenDetails.setRoleType(RoleTypeEnum.valueOf(roleType));
    authTokenDetails.setExpirationDate(expirationDate);
    authTokenDetails.setLanguage(language);
    return authTokenDetails;
}
 
Example #8
Source File: SecureUtil.java    From blade-tool with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 获取Claims
 *
 * @param request request
 * @return Claims
 */
public static Claims getClaims(HttpServletRequest request) {
	String auth = request.getHeader(SecureUtil.HEADER);
	if (StringUtil.isNotBlank(auth) && auth.length() > AUTH_LENGTH) {
		String headStr = auth.substring(0, 6).toLowerCase();
		if (headStr.compareTo(SecureUtil.BEARER) == 0) {
			auth = auth.substring(7);
			return SecureUtil.parseJWT(auth);
		}
	} else {
		String parameter = request.getParameter(SecureUtil.HEADER);
		if (StringUtil.isNotBlank(parameter)) {
			return SecureUtil.parseJWT(parameter);
		}
	}
	return null;
}
 
Example #9
Source File: KeycloakEnvironmentInitializationFilterTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shouldRetrieveTheEmailWhenItIsNotInJwtToken() throws Exception {

  Map<String, Object> claimParams = new HashMap<>();
  claimParams.put("preferred_username", "username");
  Claims claims = new DefaultClaims(claimParams).setSubject("id");
  DefaultJws<Claims> jws = new DefaultJws<>(new DefaultJwsHeader(), claims, "");
  UserImpl user = new UserImpl("id", "[email protected]", "username");
  keycloakSettingsMap.put(KeycloakConstants.USERNAME_CLAIM_SETTING, "preferred_username");
  // given
  when(tokenExtractor.getToken(any(HttpServletRequest.class))).thenReturn("token");
  when(jwtParser.parseClaimsJws(anyString())).thenReturn(jws);
  when(userManager.getById(anyString())).thenThrow(NotFoundException.class);
  when(userManager.getOrCreateUser(anyString(), anyString(), anyString())).thenReturn(user);
  keycloakAttributes.put("email", "[email protected]");

  try {
    // when
    filter.doFilter(request, response, chain);
  } catch (Exception e) {
    e.printStackTrace();
    throw e;
  }

  verify(userManager).getOrCreateUser("id", "[email protected]", "username");
}
 
Example #10
Source File: AuthFilter.java    From SpringBlade with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
	String path = exchange.getRequest().getURI().getPath();
	if (isSkip(path)) {
		return chain.filter(exchange);
	}
	ServerHttpResponse resp = exchange.getResponse();
	String headerToken = exchange.getRequest().getHeaders().getFirst(AuthProvider.AUTH_KEY);
	String paramToken = exchange.getRequest().getQueryParams().getFirst(AuthProvider.AUTH_KEY);
	if (StringUtils.isAllBlank(headerToken, paramToken)) {
		return unAuth(resp, "缺失令牌,鉴权失败");
	}
	String auth = StringUtils.isBlank(headerToken) ? paramToken : headerToken;
	String token = JwtUtil.getToken(auth);
	Claims claims = JwtUtil.parseJWT(token);
	if (claims == null) {
		return unAuth(resp, "请求未授权");
	}
	return chain.filter(exchange);
}
 
Example #11
Source File: JwtTokenAuthenticationFilter.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse rsp, FilterChain filterChain)
		throws ServletException, IOException {
	String token = req.getHeader(config.getHeader());
	if (token != null && token.startsWith(config.getPrefix() + " ")) {
		token = token.replace(config.getPrefix() + " ", "");
		try {
			Claims claims = Jwts.parser().setSigningKey(config.getSecret().getBytes()).parseClaimsJws(token)
					.getBody();
			String username = claims.getSubject();
			@SuppressWarnings("unchecked")
			List<String> authorities = claims.get("authorities", List.class);
			if (username != null) {
				UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(username, null,
						authorities.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
				SecurityContextHolder.getContext().setAuthentication(auth);
			}
		} catch (Exception ignore) {
			SecurityContextHolder.clearContext();
		}
	}
	filterChain.doFilter(req, rsp);

}
 
Example #12
Source File: JWTUtil.java    From Pixiv-Illustration-Collection-Backend with Apache License 2.0 6 votes vote down vote up
public Map<String, Object> validateToken(String token) {
   /* 成功则返回user 失败抛出未授权异常,但是如果要刷新token,我想也在这里完成,因为如果后面判断token是否过期
    就还需要再解析一次token,解token是比较消耗性能的,因此这里需要一个东西存token
    超时时间可以随着刷新自增长 最大为7天*/
    Claims claims = getAllClaimsFromToken(token);
    long difference = claims.getExpiration().getTime() - System.currentTimeMillis();
    if (difference < 0) {
        //无效 抛token过期异常
        throw new AuthExpirationException(HttpStatus.UNAUTHORIZED, "登录身份信息过期");
    }
    if (difference < authProperties.getRefreshInterval()) {
        //小于一定区间,刷新
        token = refreshToken(claims);
        claims.put("newToken", token);
    }
    return claims;
}
 
Example #13
Source File: JwtUtils.java    From withme3.0 with MIT License 6 votes vote down vote up
public static AuthUser parseJWT(String jwt) {
        if (jwt.split("\\.").length == 3) {
//            String head = jwt.split("\\.")[0];
//            String payload = jwt.split("\\.")[1];
            String sign = jwt.split("\\.")[2];
//            JwsHeader claim1 = Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(CONSTANT.SECRET_KEY)).parseClaimsJws(jwt).getHeader();
            Claims claims = Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(CONSTANT.SECRET_KEY)).parseClaimsJws(jwt).getBody();
            String newSign = createJWT(JSONObject.toJSONString(claims)).split("\\.")[2];
            if (Common.isEquals(newSign, sign)) {
//                log.info("数据一致");
//                log.info(String.valueOf(claims.get("userId")));
//                log.info((String) claims.get("userName"));
//                log.info((String) claims.get("userNickName"));
//                log.info((String) claims.get("expireTime"));
                AuthUser authUser = new AuthUser((Integer) claims.get("userId"), (String) claims.get("userName"),
                        (String) claims.get("userNickName"), Timestamp.valueOf((String) claims.get("expireTime")));
                return authUser;
            }
            return null;
        } else {
            return null;
        }
    }
 
Example #14
Source File: TokenProvider.java    From gpmr with Apache License 2.0 6 votes vote down vote up
public Authentication getAuthentication(String token) {
    Claims claims = Jwts.parser()
        .setSigningKey(secretKey)
        .parseClaimsJws(token)
        .getBody();

    Collection<? extends GrantedAuthority> authorities =
        Arrays.asList(claims.get(AUTHORITIES_KEY).toString().split(",")).stream()
            .map(SimpleGrantedAuthority::new)
            .collect(Collectors.toList());

    User principal = new User(claims.getSubject(), "",
        authorities);

    return new UsernamePasswordAuthenticationToken(principal, "", authorities);
}
 
Example #15
Source File: AuthenticationProviderTokenTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Test
public void testSerializeKeyPair() throws Exception {
    KeyPair keyPair = Keys.keyPairFor(SignatureAlgorithm.RS256);

    String privateKey = AuthTokenUtils.encodeKeyBase64(keyPair.getPrivate());
    String publicKey = AuthTokenUtils.encodeKeyBase64(keyPair.getPublic());

    String token = AuthTokenUtils.createToken(AuthTokenUtils.decodePrivateKey(Decoders.BASE64.decode(privateKey), SignatureAlgorithm.RS256),
            SUBJECT,
            Optional.empty());

    @SuppressWarnings("unchecked")
    Jwt<?, Claims> jwt = Jwts.parser()
            .setSigningKey(AuthTokenUtils.decodePublicKey(Decoders.BASE64.decode(publicKey), SignatureAlgorithm.RS256))
            .parse(token);

    assertNotNull(jwt);
    assertNotNull(jwt.getBody());
    assertEquals(jwt.getBody().getSubject(), SUBJECT);
}
 
Example #16
Source File: JwtUtil.java    From SpringBlade with Apache License 2.0 5 votes vote down vote up
/**
 * 解析jsonWebToken
 *
 * @param jsonWebToken token串
 * @return Claims
 */
public static Claims parseJWT(String jsonWebToken) {
	try {
		return Jwts.parser()
			.setSigningKey(Base64.getDecoder().decode(JwtUtil.BASE64_SECURITY))
			.parseClaimsJws(jsonWebToken).getBody();
	} catch (Exception ex) {
		return null;
	}
}
 
Example #17
Source File: _JwtTokenUtil.java    From generator-spring-rest-jwt with MIT License 5 votes vote down vote up
public String getAudienceFromToken(String token) {
    String audience;
    try {
        final Claims claims = getClaimsFromToken(token);
        audience = (String) claims.get(CLAIM_KEY_AUDIENCE);
    } catch (Exception e) {
        audience = null;
    }
    return audience;
}
 
Example #18
Source File: JwtTokenUtil.java    From spring-security with Apache License 2.0 5 votes vote down vote up
public Date getExpirationDateFromToken(String token) {
    Date expiration;
    try {
        final Claims claims = getClaimsFromToken(token);
        expiration = claims.getExpiration();
    } catch (Exception e) {
        expiration = null;
    }
    return expiration;
}
 
Example #19
Source File: JwtTokenFactory.java    From iotplatform with Apache License 2.0 5 votes vote down vote up
public SecurityUser parseAccessJwtToken(RawAccessJwtToken rawAccessToken) {
  Jws<Claims> jwsClaims = rawAccessToken.parseClaims(settings.getTokenSigningKey());
  Claims claims = jwsClaims.getBody();
  String subject = claims.getSubject();
  List<String> scopes = claims.get(SCOPES, List.class);
  if (scopes == null || scopes.isEmpty()) {
    throw new IllegalArgumentException("JWT Token doesn't have any scopes");
  }

  SecurityUser securityUser = new SecurityUser(new UserId(UUID.fromString(claims.get(USER_ID, String.class))));
  securityUser.setEmail(subject);
  securityUser.setAuthority(Authority.parse(scopes.get(0)));
  securityUser.setFirstName(claims.get(FIRST_NAME, String.class));
  securityUser.setLastName(claims.get(LAST_NAME, String.class));
  securityUser.setEnabled(claims.get(ENABLED, Boolean.class));
  boolean isPublic = claims.get(IS_PUBLIC, Boolean.class);
  UserPrincipal principal = new UserPrincipal(isPublic ? UserPrincipal.Type.PUBLIC_ID : UserPrincipal.Type.USER_NAME,
      subject);
  securityUser.setUserPrincipal(principal);
  String tenantId = claims.get(TENANT_ID, String.class);
  if (tenantId != null) {
    securityUser.setTenantId(new TenantId(UUID.fromString(tenantId)));
  }
  String customerId = claims.get(CUSTOMER_ID, String.class);
  if (customerId != null) {
    securityUser.setCustomerId(new CustomerId(UUID.fromString(customerId)));
  }

  return securityUser;
}
 
Example #20
Source File: JwtTokenUtil.java    From spring-security with Apache License 2.0 5 votes vote down vote up
public String refreshToken(String token) {
    String refreshedToken;
    try {
        final Claims claims = getClaimsFromToken(token);
        claims.put(CLAIM_KEY_CREATED, new Date());
        refreshedToken = generateToken(claims);
    } catch (Exception e) {
        refreshedToken = null;
    }
    return refreshedToken;
}
 
Example #21
Source File: AgentServiceImpl.java    From DrivingAgency with MIT License 5 votes vote down vote up
@Override
public AgentBaseInfoVo logout(String token) {
    Preconditions.checkArgument(StringUtils.isNotBlank(token),"token不能为空");
    try {
        Claims claims = TokenUtil.parseJWT(token);
        stringRedisTemplate.opsForHash().put(DrivingConstant.Redis.TOKEN_INVALID, token, DateTimeUtil.dateToMillis(new Date()));
        UserTokenDto userTokenDto= JsonSerializerUtil.string2Obj(claims.getSubject(),UserTokenDto.class);
        AgentBaseInfoVo agentBaseInfoVo=new AgentBaseInfoVo();
        BeanUtils.copyProperties(userTokenDto,agentBaseInfoVo);
        return agentBaseInfoVo;
    }catch (Exception e){
        log.error("登出失败:{}",e);
    }
    return null;
}
 
Example #22
Source File: JwtTokenUtil.java    From ywh-frame with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 从令牌中获取用户名
 *
 * @param token 令牌
 * @return 用户名
 */
public String getUsernameFromToken(String token) {
    String username;
    try {
        Claims claims = getClaimsFromToken(token);
        username = claims.getSubject();
    } catch (Exception e) {
        username = null;
    }
    return username;
}
 
Example #23
Source File: PreFilter.java    From NetworkDisk_Storage with GNU General Public License v2.0 5 votes vote down vote up
private void verifyToken(RequestContext ctx) {
    try {
        String token = CookieUtils.getCookie("token");
        Claims claims = JWTUtils.parseJWT(token, "nimadetou".getBytes());
        String subject = claims.getSubject();
        UserInfoDTO userinfo = JSONUtils.parseObject(subject, UserInfoDTO.class);
        log.info(userinfo.getUserId());
        ctx.setSendZuulResponse(true);
    } catch (Exception e) {
        ctx.setSendZuulResponse(false);
    }
}
 
Example #24
Source File: JwtTokenProvider.java    From Spring-Boot-Blog-REST-API with GNU Affero General Public License v3.0 5 votes vote down vote up
public Long getUserIdFromJWT(String token){
    Claims claims = Jwts.parser()
            .setSigningKey(jwtSecret)
            .parseClaimsJws(token)
            .getBody();

    return Long.valueOf(claims.getSubject());
}
 
Example #25
Source File: JwtTokenUtil.java    From tour-of-heros-api-security-zerhusen with MIT License 5 votes vote down vote up
public Date getExpirationDateFromToken(String token) {
    Date expiration;
    try {
        final Claims claims = getClaimsFromToken(token);
        expiration = claims.getExpiration();
    } catch (Exception e) {
        expiration = null;
    }
    return expiration;
}
 
Example #26
Source File: JwtTokenUtil.java    From microservices-sample-project with Apache License 2.0 5 votes vote down vote up
public Date getExpirationDateFromToken(String token) {
    Date expiration;
    try {
        final Claims claims = getClaimsFromToken(token);
        expiration = claims.getExpiration();
    } catch (Exception e) {
        expiration = null;
    }
    return expiration;
}
 
Example #27
Source File: JwtService.java    From nifi with Apache License 2.0 5 votes vote down vote up
public String getAuthenticationFromToken(final String base64EncodedToken) throws JwtException {
    // The library representations of the JWT should be kept internal to this service.
    try {
        final Jws<Claims> jws = parseTokenFromBase64EncodedString(base64EncodedToken);

        if (jws == null) {
            throw new JwtException("Unable to parse token");
        }

        // Additional validation that subject is present
        if (StringUtils.isEmpty(jws.getBody().getSubject())) {
            throw new JwtException("No subject available in token");
        }

        // TODO: Validate issuer against active registry?
        if (StringUtils.isEmpty(jws.getBody().getIssuer())) {
            throw new JwtException("No issuer available in token");
        }
        return jws.getBody().getSubject();
    } catch (JwtException e) {
        logger.debug("The Base64 encoded JWT: " + base64EncodedToken);
        final String errorMessage = "There was an error validating the JWT";

        // A common attack is someone trying to use a token after the user is logged out
        // No need to show a stacktrace for an expected and handled scenario
        String causeMessage = e.getLocalizedMessage();
        if (e.getCause() != null) {
            causeMessage += "\n\tCaused by: " + e.getCause().getLocalizedMessage();
        }
        if (logger.isDebugEnabled()) {
            logger.error(errorMessage, e);
        } else {
            logger.error(errorMessage);
            logger.error(causeMessage);
        }
        throw e;
    }
}
 
Example #28
Source File: JwtTokenUtil.java    From hdw-dubbo with Apache License 2.0 5 votes vote down vote up
/**
 * 从token中获取JWT中的负载
 */
private  Claims getClaimsFromToken(String token) {
    Claims claims = null;
    try {
        claims = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    } catch (Exception e) {
        LOGGER.error("JWT格式验证失败:{}", token);
    }
    return claims;
}
 
Example #29
Source File: JwtTokenUtils.java    From spring-admin-vue with Apache License 2.0 5 votes vote down vote up
/**
 * 从令牌中获取用户名
 *
 * @param token 令牌
 * @return 用户名
 */
public String getUsernameFromToken(String token) {
    String username;
    try {
        Claims claims = getClaimsFromToken(token);
        username = claims.getSubject();
    } catch (Exception e) {
        username = null;
    }
    return username;
}
 
Example #30
Source File: JwtTokenUtil.java    From SpringBootLearn with Apache License 2.0 5 votes vote down vote up
/**
 * 根据token 获取用户ID
 * @param token
 * @return
 */
private int getUserIdFromToken(String token) {
    int userId;
    try {
        final Claims claims = getClaimsFromToken(token);
        userId = Integer.parseInt(String.valueOf(claims.get(CLAIM_KEY_USER_ID)));
    } catch (Exception e) {
        userId = 0;
    }
    return userId;
}