com.auth0.jwt.interfaces.Claim Java Examples

The following examples show how to use com.auth0.jwt.interfaces.Claim. 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: JwtApplication.java    From spring-boot-study with MIT License 6 votes vote down vote up
/**
 * 验证 token
 * */
private static void verifyJWTToken(String token) throws JWTVerificationException {
    Algorithm algorithm=Algorithm.HMAC256("secret");
    JWTVerifier verifier = JWT.require(algorithm)
            .withIssuer("SERVICE")
            .build();

    DecodedJWT jwt =verifier.verify(token);
    String subject=jwt.getSubject();
    Map<String,Claim> claims=jwt.getClaims();
    Claim claim = claims.get("loginName");
    System.out.println("自定义 claim:"+claim.asString());

    List<String> audience = jwt.getAudience();
    System.out.println("subject 值:"+subject);
    System.out.println("audience 值:"+audience.get(0));
}
 
Example #2
Source File: MachineController.java    From onenet-iot-project with MIT License 6 votes vote down vote up
/**
 * 获取机器设备列表
 *
 * @param request 请求
 * @return Response
 */
@GetMapping
public Response getMachineList(HttpServletRequest request) {
    String token = request.getHeader("token");
    if (!VerifyUtil.checkString(token)) {
        return ResultUtil.returnStatus(ResponseStatus.NOT_LOGIN);
    } else {
        try {
            // 解析token
            Claim claim = tokenUtil.getClaim(token, "account_id");
            Account account = accountService.findAccountById(claim.asString());
            // 判断角色是否有权限
            if (account != null && account.getRole() == Role.ADMIN) {
                List<Machine> machines = machineService.findAllMachine();
                log.info("machines: {}", machines);
                return ResultUtil.returnStatusAndData(ResponseStatus.SUCCESS, machines);
            } else {
                return ResultUtil.returnStatus(ResponseStatus.VISITED_FORBID);
            }
        } catch (JWTVerificationException e) {
            // 解析失败,token无效
            log.error("{}", e);
            return ResultUtil.returnStatus(ResponseStatus.NOT_LOGIN);
        }
    }
}
 
Example #3
Source File: JwtManager.java    From Mars-Java with MIT License 6 votes vote down vote up
/**
 * 根据Token获取存进去的对象
 * @param token
 * @param cls
 * @param <T>
 * @return obj
 */
public <T> T  getObject(String token,Class<T> cls) {
    JSONObject json = new JSONObject();
    try {
        Map<String, Claim> claims = decryptToken(token);
        if(claims == null || claims.isEmpty()){
            return null;
        }
        for (String key : claims.keySet()) {
            json.put(key, claims.get(key).asString());
        }
        return json.toJavaObject(cls);
    } catch (Exception e) {
        return null;
    }
}
 
Example #4
Source File: JWTSsoService.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public String readUserIdentifier(HttpServletRequest request) {
	try {
		String jwtToken = request.getParameter(SsoServiceInterface.USER_ID);
		if (jwtToken == null) {
			logger.debug("JWT token not found in request");
			return null;
		}
		LogMF.debug(logger, "JWT token in input is [{0}]", jwtToken);
		JWTVerifier verifier = JWT.require(algorithm).build();
		DecodedJWT decodedJWT = verifier.verify(jwtToken);
		logger.debug("JWT token verified properly");
		Claim userIdClaim = decodedJWT.getClaim(SsoServiceInterface.USER_ID);
		LogMF.debug(logger, "User id detected is [{0}]", userIdClaim.asString());
		assertNotEmpty(userIdClaim, "User id information is missing!!!");
		return jwtToken;
	} catch (JWTVerificationException e) {
		throw new SpagoBIRuntimeException("Invalid JWT token!", e);
	}
}
 
Example #5
Source File: JsonNodeClaimTest.java    From java-jwt with MIT License 6 votes vote down vote up
@Test
public void shouldGetMapValue() throws Exception {
    Map<String, Object> map = new HashMap<>();
    map.put("text", "extraValue");
    map.put("number", 12);
    map.put("boolean", true);
    map.put("object", Collections.singletonMap("something", "else"));

    JsonNode value = mapper.valueToTree(map);
    Claim claim = claimFromNode(value);

    assertThat(claim, is(notNullValue()));
    Map<String, Object> backMap = claim.asMap();
    assertThat(backMap, is(notNullValue()));
    assertThat(backMap, hasEntry("text", (Object) "extraValue"));
    assertThat(backMap, hasEntry("number", (Object) 12));
    assertThat(backMap, hasEntry("boolean", (Object) true));
    assertThat(backMap, hasKey("object"));
    assertThat((Map<String, Object>) backMap.get("object"), IsMapContaining.hasEntry("something", (Object) "else"));
}
 
Example #6
Source File: Token.java    From Mall-Server with MIT License 6 votes vote down vote up
/**
 * 解密token
 * @param token jwt类型的token
 * @param classT 加密时的类型
 * @param <T>
 * @return 返回解密后的对象 - 如果token过期返回空对象
 */
public static <T> T validToken(String token, Class<T> classT)  {
    DecodedJWT decode = null;
    try {
        decode = JWT.decode(token);
        Map<String, Claim> claims = decode.getClaims();
        if (claims.containsKey(EXP) && claims.containsKey(PAYLOAD)){
            long tokenTime = claims.get(EXP).asDate().getTime();
            long nowTime = new Date().getTime();
            // 判断令牌是否超时
            if (tokenTime > nowTime){
                String json = claims.get(PAYLOAD).asString();
                if (classT != null) {
                    return JSON.parseObject(json, classT);
                } else {
                    return (T) JSON.parse(json);
                }
            }
        }
    } catch (Exception e) {
        System.out.println(e);
        return null;
    }
    return null;
}
 
Example #7
Source File: LoginFilter.java    From bookmark with MIT License 6 votes vote down vote up
private boolean checkJwt(String jwt) {
    if (StringUtil.isEmpty(jwt)) {
        log.error("jwt为空");
        return false;
    }
    try {
        Map<String, Claim> map = JwtUtil.decode(jwt, secret);
        int userId = Integer.parseInt(map.get("userId").asString());
        UserContext context = new UserContext();
        context.setJwt(jwt);
        context.setUserId(userId);
        UserContextHolder.set(context);
        return true;
    } catch (Exception e) {
        log.error("jwt解密失败:{},原因:{}", jwt, e.getMessage());
        return false;
    }
}
 
Example #8
Source File: JsonNodeClaimTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldThrowIfListClassMismatch() throws Exception {
    JsonNode value = mapper.valueToTree(new String[]{"keys", "values"});
    Claim claim = claimFromNode(value);

    exception.expect(JWTDecodeException.class);
    claim.asList(UserPojo.class);
}
 
Example #9
Source File: JwtSessionConfigurator.java    From aceql-http with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
    * Extracts the Database from the decoded JWT.
    */
   @Override
   public String getDatabase(String sessionId) {
try {
    DecodedJWT jwt = JWT.decode(sessionId);
    Map<String, Claim> claims = jwt.getClaims(); // Key is the Claim
						 // name
    Claim claim = claims.get("dbn");
    return claim.asString();

} catch (JWTDecodeException exception) {
    System.err.println(exception);
    return null;
}
   }
 
Example #10
Source File: OpenIdAuthenticationManager.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
public OpenIdAlfioUser retrieveUserInfo(String code) {
    log.trace("Attempting to retrieve Access Token");
    var accessTokenResponse = retrieveAccessToken(code);
    String idToken = (String) accessTokenResponse.get(ID_TOKEN);

    Map<String, Claim> idTokenClaims = JWT.decode(idToken).getClaims();
    String subject = idTokenClaims.get(SUBJECT).asString();
    String email = idTokenClaims.get(EMAIL).asString();
    List<String> groupsList = idTokenClaims.get(openIdConfiguration().getRolesParameter()).asList(String.class);
    log.trace("IdToken contains the following groups: {}", groupsList);
    List<String> groups = groupsList.stream().filter(group -> group.startsWith("ALFIO_")).collect(Collectors.toList());
    boolean isAdmin = groups.contains(ALFIO_ADMIN);

    if (isAdmin) {
        log.trace("User is admin");
        return new OpenIdAlfioUser(idToken, subject, email, true, Set.of(Role.ADMIN), null);
    }

    log.trace("User is NOT admin");

    if(groups.isEmpty()){
        String message = "Users must have at least a group called ALFIO_ADMIN or ALFIO_BACKOFFICE";
        logger.error(message);
        throw new RuntimeException(message);
    }

    List<String> alfioOrganizationAuthorizationsRaw = idTokenClaims.get(openIdConfiguration().getAlfioGroupsParameter()).asList(String.class);
    log.trace("IdToken contains the following alfioGroups: {}", alfioOrganizationAuthorizationsRaw);
    Map<String, Set<String>> alfioOrganizationAuthorizations = extractOrganizationRoles(alfioOrganizationAuthorizationsRaw);
    Set<Role> alfioRoles = extractAlfioRoles(alfioOrganizationAuthorizations);
    return new OpenIdAlfioUser(idToken, subject, email, false, alfioRoles, alfioOrganizationAuthorizations);
}
 
Example #11
Source File: JsonNodeClaimTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldGetBooleanValue() throws Exception {
    JsonNode value = mapper.valueToTree(true);
    Claim claim = claimFromNode(value);

    assertThat(claim.asBoolean(), is(notNullValue()));
    assertThat(claim.asBoolean(), is(true));
}
 
Example #12
Source File: PayloadImplTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldNotAllowToModifyClaimsMap() throws Exception {
    assertThat(payload, is(notNullValue()));
    Map<String, Claim> claims = payload.getClaims();
    assertThat(claims, is(notNullValue()));
    exception.expect(UnsupportedOperationException.class);
    claims.put("name", null);
}
 
Example #13
Source File: PayloadImplTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldGetClaims() throws Exception {
    Map<String, JsonNode> tree = new HashMap<>();
    tree.put("extraClaim", new TextNode("extraValue"));
    tree.put("sub", new TextNode("auth0"));
    PayloadImpl payload = new PayloadImpl(null, null, null, null, null, null, null, tree, objectReader);
    assertThat(payload, is(notNullValue()));
    Map<String, Claim> claims = payload.getClaims();
    assertThat(claims, is(notNullValue()));

    assertThat(claims.get("extraClaim"), is(notNullValue()));
    assertThat(claims.get("sub"), is(notNullValue()));
}
 
Example #14
Source File: JsonNodeClaimTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldReturnNonNullClaimWhenParsingDoubleValue() throws Exception {
    JsonNode value = mapper.valueToTree(Double.MAX_VALUE);
    Claim claim = claimFromNode(value);

    assertThat(claim, is(notNullValue()));
    assertThat(claim, is(instanceOf(JsonNodeClaim.class)));
    assertThat(claim.isNull(), is(false));
}
 
Example #15
Source File: JsonNodeClaim.java    From java-jwt with MIT License 5 votes vote down vote up
/**
 * Helper method to create a Claim representation from the given JsonNode.
 *
 * @param node the JsonNode to convert into a Claim.
 * @return a valid Claim instance. If the node is null or missing, a NullClaim will be returned.
 */
static Claim claimFromNode(JsonNode node, ObjectReader objectReader) {
    if (node == null || node.isNull() || node.isMissingNode()) {
        return new NullClaim();
    }
    return new JsonNodeClaim(node, objectReader);
}
 
Example #16
Source File: PayloadImpl.java    From java-jwt with MIT License 5 votes vote down vote up
@Override
public Map<String, Claim> getClaims() {
    Map<String, Claim> claims = new HashMap<>(tree.size() * 2);
    for (String name : tree.keySet()) {
        claims.put(name, extractClaim(name, tree, objectReader));
    }
    return Collections.unmodifiableMap(claims);
}
 
Example #17
Source File: JsonNodeClaimTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldReturnNonNullClaimWhenParsingArray() throws Exception {
    JsonNode value = mapper.valueToTree(new String[]{});
    Claim claim = claimFromNode(value);

    assertThat(claim, is(notNullValue()));
    assertThat(claim, is(instanceOf(JsonNodeClaim.class)));
    assertThat(claim.isNull(), is(false));
}
 
Example #18
Source File: JwtManager.java    From Mars-Java with MIT License 5 votes vote down vote up
/**
 * 解密Token
 *
 * @param token
 * @return map
 */
private Map<String, Claim> decryptToken(String token) {
    DecodedJWT jwt = null;
    try {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        jwt = verifier.verify(token);
        return jwt.getClaims();
    } catch (Exception e) {
        return null;
    }
}
 
Example #19
Source File: AuthServiceImpl.java    From smockin with Apache License 2.0 5 votes vote down vote up
public void checkTokenRoles(final String jwt, SmockinUserRoleEnum... roles) throws AuthException {

        final DecodedJWT decodedJWT = jwtVerifier.verify(jwt);
        final Claim roleClaim = decodedJWT.getClaim(jwtRoleKey);

        if (roleClaim == null || !Stream.of(roles).anyMatch(r -> r.name().equals(roleClaim.asString()))) {
            throw new AuthException();
        }
    }
 
Example #20
Source File: JwtSessionConfigurator.java    From aceql-http with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
    * Extracts the username from the decoded JWT.
    */
   @Override
   public String getUsername(String sessionId) {
try {
    DecodedJWT jwt = JWT.decode(sessionId);
    Map<String, Claim> claims = jwt.getClaims(); // Key is the Claim
						 // name
    Claim claim = claims.get("usr");
    return claim.asString();

} catch (JWTDecodeException exception) {
    exception.printStackTrace();
    return null;
}
   }
 
Example #21
Source File: AuthenticationFactory.java    From MicroCommunity with Apache License 2.0 5 votes vote down vote up
/**
 * 校验Token
 *
 * @param token
 * @return
 * @throws Exception
 */
public static Map<String, String> verifyToken(String token) throws Exception {
    String jwtSecret = MappingCache.getValue(MappingConstant.KEY_JWT_SECRET);
    if (StringUtil.isNullOrNone(jwtSecret)) {
        jwtSecret = CommonConstant.DEFAULT_JWT_SECRET;
    }
    Algorithm algorithm = Algorithm.HMAC256(jwtSecret);
    JWTVerifier verifier = JWT.require(algorithm).withIssuer("java110").build();
    DecodedJWT jwt = verifier.verify(token);
    String jdi = jwt.getId();
    //保存token Id
    String userId = JWTCache.getValue(jdi);
    if (StringUtil.isNullOrNone(userId)) {
        throw new JWTVerificationException("用户还未登录");
    }
    String expireTime = MappingCache.getValue(MappingConstant.KEY_JWT_EXPIRE_TIME);
    if (StringUtil.isNullOrNone(expireTime)) {
        expireTime = CommonConstant.DEFAULT_JWT_EXPIRE_TIME;
    }
    //刷新过时时间
    JWTCache.resetExpireTime(jdi, Integer.parseInt(expireTime));
    Map<String, Claim> claims = jwt.getClaims();
    // Add the claim to request header
    Map<String, String> paramOut = new HashMap<String, String>();
    for (String key : claims.keySet()) {
        paramOut.put(key, claims.get(key).asString());
    }
    paramOut.put(CommonConstant.LOGIN_USER_ID, userId);
    return paramOut;
}
 
Example #22
Source File: JsonNodeClaimTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldGetCustomClassValue() throws Exception {
    JsonNode value = mapper.valueToTree(new UserPojo("john", 123));
    Claim claim = claimFromNode(value);

    assertThat(claim, is(notNullValue()));
    assertThat(claim.as(UserPojo.class).getName(), is("john"));
    assertThat(claim.as(UserPojo.class).getId(), is(123));
}
 
Example #23
Source File: JwtService.java    From demo-project with MIT License 5 votes vote down vote up
/**
 * 过期时间小于半小时,返回新的jwt,否则返回原jwt
 * @param jwt
 * @return
 */
public String refreshJwt(String jwt){
    String secret = RedisUtil.redisTemplate.opsForValue().get(jwt);
    Map<String, Claim> map = JwtUtil.decode(jwt,secret);
    if(map.get("exp").asLong()*1000 - System.currentTimeMillis()/1000<30*60*1000){
        return this.generateNewJwt(map.get("name").asString());
    }else{
        return jwt;
    }
}
 
Example #24
Source File: JWTTokenManager.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
@Override
public UUID getJobIdFromToken(String token) {
  try {
    DecodedJWT jwt = verifier.verify(token);
    // Token is verified, get claim
    Claim claim = jwt.getClaim(JWTTokenManager.ID_CLAIM_KEY);
    if (claim.isNull()) {
      return null;
    }
    return claim.isNull() ? null : UUID.fromString(claim.asString());
  } catch (JWTVerificationException exception) {
    monitor.debug(() -> "Error verifying token", exception);
    throw new RuntimeException("Error verifying token: " + token);
  }
}
 
Example #25
Source File: JwtHelper.java    From litemall with MIT License 5 votes vote down vote up
public Integer verifyTokenAndGetUserId(String token) {
		try {
		    Algorithm algorithm = Algorithm.HMAC256(SECRET);
		    JWTVerifier verifier = JWT.require(algorithm)
		        .withIssuer(ISSUSER)
		        .build();
		    DecodedJWT jwt = verifier.verify(token);
		    Map<String, Claim> claims = jwt.getClaims();
		    Claim claim = claims.get("userId");
		    return claim.asInt();
		} catch (JWTVerificationException exception){
//			exception.printStackTrace();
		}
		
		return 0;
	}
 
Example #26
Source File: JWTAuthentication.java    From codeway_service with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 解析JWT,获取claims
 * @param jwtStr:待解密的jwt
 * @return
 */
public static Map<String, String> parseJwtToClaims(String jwtStr)  {
	DecodedJWT jwt = JWT.decode(jwtStr);
	Map<String, Claim> map = jwt.getClaims();
	Map<String, String> resultMap = Maps.newHashMap();
	map.forEach((k,v) -> resultMap.put(k, v.asString()));
	return resultMap;
}
 
Example #27
Source File: JwtTokenService.java    From singleton with Eclipse Public License 2.0 5 votes vote down vote up
public  Map<String, Claim> verifyToken(String token) throws Exception{
	JWTVerifier verifier = null;
	verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
	DecodedJWT decoded = null;
	try {
	    decoded = verifier.verify(token);
	} catch (Exception e) {
		// TODO Auto-generated catch block
		logger.error(e.getMessage(), e);
		throw new RuntimeException(e);
	} 

  return decoded.getClaims();
}
 
Example #28
Source File: JsonNodeClaimTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldReturnBaseClaimWhenParsingNullValue() throws Exception {
    JsonNode value = mapper.valueToTree(null);
    Claim claim = claimFromNode(value);

    assertThat(claim, is(notNullValue()));
    assertThat(claim, is(instanceOf(NullClaim.class)));
    assertThat(claim.isNull(), is(true));
}
 
Example #29
Source File: JwtPrincipal.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
public JwtPrincipal(DecodedJWT decodedJWT, String credentials) {
    this.hashcode = MurmurHash3.hash32(credentials);
    this.subject = decodedJWT.getSubject();
    this.audience = decodedJWT.getAudience();
    Map<String, Claim> claims = decodedJWT.getClaims();
    this.serviceAccounts = new HashSet<>(decodedJWT.getClaim("sas").asList(String.class));
    this.organizations = new HashSet<>(decodedJWT.getClaim("orgs").asList(String.class));
    if (claims.containsKey("roles")) {
        this.roles = new HashSet<>(decodedJWT.getClaim("roles").asList(String.class));
    }
    if (claims.containsKey("authorities")) {
        this.authorities = new HashSet<>(decodedJWT.getClaim("authorities").asList(String.class));
    }
}
 
Example #30
Source File: SimpleJwtToken.java    From keeper with Apache License 2.0 5 votes vote down vote up
@Override
public boolean canRenew(String token) {
    if (StringUtil.isEmpty(token)) {
        return false;
    }

    Long expiresAt = this.parseToken(token)
            .map(decode -> decode.getClaim(REFRESH_EXPIRES_AT))
            .map(Claim::asLong)
            .orElse(0L);

    long now = Instant.now().getEpochSecond();
    return expiresAt > now;
}