Java Code Examples for com.auth0.jwt.algorithms.Algorithm#HMAC256

The following examples show how to use com.auth0.jwt.algorithms.Algorithm#HMAC256 . 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: AuthenticationFactory.java    From MicroCommunity with Apache License 2.0 6 votes vote down vote up
/**
 * 删除Token
 *
 * @param token
 * @return
 * @throws Exception
 */
public static void deleteToken(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)) { //说明redis中jdi 已经失效
        JWTCache.removeValue(jdi);
    }
}
 
Example 2
Source File: JWTDemo.java    From springbootexamples with Apache License 2.0 6 votes vote down vote up
@Test
public void createToken() {

	String secret = "secret";// token 密钥
	Algorithm algorithm = Algorithm.HMAC256("secret");

	// 头部信息
	Map<String, Object> map = new HashMap<String, Object>();
	map.put("alg", "HS256");
	map.put("typ", "JWT");

	Date nowDate = new Date();
	Date expireDate = getAfterDate(nowDate, 0, 0, 0, 2, 0, 0);// 2小过期
	
	String token = JWT.create()
		.withHeader(map)// 设置头部信息 Header 
		.withIssuer("SERVICE")//设置 载荷 签名是有谁生成 例如 服务器
		.withSubject("this is test token")//设置 载荷 签名的主题
		// .withNotBefore(new Date())//设置 载荷 定义在什么时间之前,该jwt都是不可用的.
		.withAudience("APP")//设置 载荷 签名的观众 也可以理解谁接受签名的
		.withIssuedAt(nowDate) //设置 载荷 生成签名的时间
		.withExpiresAt(expireDate)//设置 载荷 签名过期的时间
		.sign(algorithm);//签名 Signature
	Assert.assertTrue(token.length() > 0);
}
 
Example 3
Source File: OAuth2AuthenticationResourceTest.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
private void verifyJwtToken(Response response) throws NoSuchAlgorithmException, InvalidKeyException, IOException, SignatureException, JWTVerificationException {
    Token responseToken = response.readEntity(Token.class);
    assertEquals("BEARER", responseToken.getTokenType().name());

    String token = responseToken.getToken();

    Algorithm algorithm = Algorithm.HMAC256("myJWT4Gr4v1t33_S3cr3t");
    JWTVerifier jwtVerifier = JWT.require(algorithm).build();

    DecodedJWT jwt = jwtVerifier.verify(token);

    assertEquals(jwt.getSubject(),"[email protected]");

    assertEquals("Jane", jwt.getClaim("firstname").asString());
    assertEquals("gravitee-management-auth", jwt.getClaim("iss").asString());
    assertEquals("[email protected]", jwt.getClaim("sub").asString());
    assertEquals("[email protected]", jwt.getClaim("email").asString());
    assertEquals("Doe", jwt.getClaim("lastname").asString());
}
 
Example 4
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 5
Source File: JwtUtil.java    From demo-project with MIT License 5 votes vote down vote up
/**
 * Description: 解密jwt
 *
 * @param token  token
 * @param secret secret
 * @return java.util.Map<java.lang.String                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               ,                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               com.auth0.jwt.interfaces.Claim>
 * @author fanxb
 * @date 2019/3/4 18:14
 */
public static Map<String, Claim> decode(String token, String secret) {
    if (token == null || token.length() == 0) {
        throw new CustomException("token为空:" + token);
    }
    Algorithm algorithm = Algorithm.HMAC256(secret);
    JWTVerifier jwtVerifier = JWT.require(algorithm).build();
    DecodedJWT decodedJWT = jwtVerifier.verify(token);
    return decodedJWT.getClaims();
}
 
Example 6
Source File: JwtUtil.java    From watchdog-framework with MIT License 5 votes vote down vote up
/**
 * 校验token是否正确
 * @param token 密钥
 * @param secret 用户的密码
 * @return 是否正确
 */
public static boolean verify(String token, String username, String secret) {
    try {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier verifier = JWT.require(algorithm)
                .withClaim("username", username)
                .build();
        verifier.verify(token);
        return true;
    } catch (Exception exception) {
        return false;
    }
}
 
Example 7
Source File: JwtUtil.java    From watchdog-framework with MIT License 5 votes vote down vote up
/**
 * 生成签名,5min后过期
 * @param username 用户名
 * @param secret 用户的密码
 * @return 加密的token
 */
public static String sign(String uid,String username, String secret) {
    try {
        Date date = new Date(System.currentTimeMillis()+EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(secret);
        // 附带username信息
        return JWT.create()
                .withClaim("uid", uid)
                .withClaim("username", username)
                .withExpiresAt(date)
                .sign(algorithm);
    } catch (UnsupportedEncodingException e) {
        return null;
    }
}
 
Example 8
Source File: DisallowAnonymousFilter.java    From waltz with Apache License 2.0 5 votes vote down vote up
public DisallowAnonymousFilter(SettingsService settingsService) {
    super(settingsService);
    try {
        Algorithm algorithm = Algorithm.HMAC256(JWTUtilities.SECRET);
        verifier = JWT.require(algorithm)
                .withIssuer(JWTUtilities.ISSUER)
                .build(); //Reusable verifier instance
    } catch (Exception e) {
        LOG.error("Cannot create JWT Verifier, this is bad", e);
        throw new UnsupportedOperationException(e);
    }
}
 
Example 9
Source File: AlgorithmLinker.java    From JWT4B with GNU General Public License v3.0 5 votes vote down vote up
private static Algorithm getAlgorithm(String algo, String key, boolean IsKeyASignerKey)
		throws IllegalArgumentException, UnsupportedEncodingException {
	if (algo.equals(HS256.getAlgorithm())) {
		return Algorithm.HMAC256(key);
	}
	if (algo.equals(HS384.getAlgorithm())) {
		return Algorithm.HMAC384(key);
	}
	if (algo.equals(HS512.getAlgorithm())) {
		return Algorithm.HMAC512(key);
	}
	if (algo.equals(ES256.getAlgorithm())) {
		return Algorithm.ECDSA256((ECKey) getKeyInstance(key, "EC", IsKeyASignerKey));
	}
	if (algo.equals(ES384.getAlgorithm())) {
		return Algorithm.ECDSA384((ECKey) getKeyInstance(key, "EC", IsKeyASignerKey));
	}
	if (algo.equals(ES512.getAlgorithm())) {
		return Algorithm.ECDSA512((ECKey) getKeyInstance(key, "EC",IsKeyASignerKey));
	}
	if (algo.equals(RS256.getAlgorithm())) {
		return Algorithm.RSA256((RSAKey) getKeyInstance(key, "RSA", IsKeyASignerKey));
	}
	if (algo.equals(RS384.getAlgorithm())) {
		return Algorithm.RSA384((RSAKey) getKeyInstance(key, "RSA", IsKeyASignerKey));
	}
	if (algo.equals(RS512.getAlgorithm())) {
		return Algorithm.RSA512((RSAKey) getKeyInstance(key, "RSA", IsKeyASignerKey));
	}

	return Algorithm.none();
}
 
Example 10
Source File: JwtUtil.java    From demo-project with MIT License 5 votes vote down vote up
/**
 * Description: 生成一个jwt字符串
 *
 * @param name    用户名
 * @param secret  秘钥
 * @param timeOut 超时时间(单位s)
 * @return java.lang.String
 * @author fanxb
 * @date 2019/3/4 17:26
 */
public static String encode(String name, String secret, long timeOut) {
    Algorithm algorithm = Algorithm.HMAC256(secret);
    String token = JWT.create()
            //设置过期时间为一个小时
            .withExpiresAt(new Date(System.currentTimeMillis() + timeOut))
            //设置负载
            .withClaim("name", name)
            .sign(algorithm);
    return token;
}
 
Example 11
Source File: JwtUtil.java    From ProjectStudy with MIT License 5 votes vote down vote up
/**
 * 生成签名
 *
 * @param account 帐号
 * @param secret  私钥
 * @return java.lang.String 返回加密的Token
 * @author Wang926454
 * @date 2018/8/31 9:07
 */
public static String sign(String account, String secret) {
    try {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(secret);
        // 附带account帐号信息
        return JWT.create()
                .withClaim("account", account)
                .withExpiresAt(date)
                .sign(algorithm);
    } catch (UnsupportedEncodingException e) {
        e.getMessage();
    }
    return null;
}
 
Example 12
Source File: JwtUtil.java    From flash-waimai with MIT License 5 votes vote down vote up
/**
 * 生成签名,5min后过期
 * @param user 用户
 * @return 加密的token
 */
public static String sign(User user) {
    try {
        Date date = new Date(System.currentTimeMillis()+EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(user.getPassword());
        // 附带username信息
        return JWT.create()
                .withClaim("username", user.getAccount())
                .withClaim("userId",user.getId())
                .withExpiresAt(date)
                .sign(algorithm);
    } catch (UnsupportedEncodingException e) {
        return null;
    }
}
 
Example 13
Source File: JwtUtil.java    From jeecg-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 校验token是否正确
 *
 * @param token  密钥
 * @param secret 用户的密码
 * @return 是否正确
 */
public static boolean verify(String token, String username, String secret) {
	try {
		// 根据密码生成JWT效验器
		Algorithm algorithm = Algorithm.HMAC256(secret);
		JWTVerifier verifier = JWT.require(algorithm).withClaim("username", username).build();
		// 效验TOKEN
		DecodedJWT jwt = verifier.verify(token);
		return true;
	} catch (Exception exception) {
		return false;
	}
}
 
Example 14
Source File: AuthSign.java    From charging_pile_cloud with MIT License 5 votes vote down vote up
/**
 * 获取用户id信息
 */
public  static Long  getUserId(String token) {
    try {
        Algorithm algorithm= Algorithm.HMAC256(SECRET);
        JWTVerifier verifier=JWT.require(algorithm).build();
        DecodedJWT jwt=verifier.verify(token);
       return jwt.getClaim(ID).asLong();
    } catch (Exception e) {
       log.info("获取用户id错误:%s", ExceptionUtils.getStackTrace(e));
    }
    return 0L;
}
 
Example 15
Source File: JWTUtil.java    From SpringAll with MIT License 5 votes vote down vote up
/**
 * 生成 token
 *
 * @param username 用户名
 * @param secret   用户的密码
 * @return token
 */
public static String sign(String username, String secret) {
    try {
        username = StringUtils.lowerCase(username);
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(secret);
        return JWT.create()
                .withClaim("username", username)
                .withExpiresAt(date)
                .sign(algorithm);
    } catch (Exception e) {
        log.error("error:{}", e);
        return null;
    }
}
 
Example 16
Source File: TokenUtil.java    From onenet-iot-project with MIT License 4 votes vote down vote up
/**
 * 创建jwt串
 *
 * @param map     自定义的 K, V
 * @param expires 过期时间(ms)
 * @return token串
 * @throws JWTCreationException
 */
public String createJwt(Map<String, String> map, long expires) throws JWTCreationException {

    Algorithm algorithm = Algorithm.HMAC256(env.getProperty("jwt.secret-key"));

    JWTCreator.Builder builder = JWT.create()
            .withIssuer(env.getProperty("jwt.issuer"))
            .withSubject(env.getProperty("jwt.subject"))
            .withExpiresAt(new Date(System.currentTimeMillis() + expires));

    for (Map.Entry<String, String> entry : map.entrySet()) {
        builder.withClaim(entry.getKey(), entry.getValue());
    }
    return builder.sign(algorithm);
}
 
Example 17
Source File: AbstractAuthenticationResource.java    From gravitee-management-rest-api with Apache License 2.0 4 votes vote down vote up
protected Response connectUser(String userId,final String state, final HttpServletResponse servletResponse) {
    UserEntity user = userService.connect(userId);

    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    final UserDetails userDetails = (UserDetails) authentication.getPrincipal();

    // Manage authorities, initialize it with dynamic permissions from the IDP
    List<Map<String, String>> authorities = userDetails.getAuthorities().stream().map(authority -> Maps.<String, String>builder().put("authority", authority.getAuthority()).build()).collect(Collectors.toList());

    // We must also load permissions from repository for configured management or portal role
    Set<RoleEntity> userRoles = membershipService.getRoles(
            MembershipReferenceType.ENVIRONMENT,
            GraviteeContext.getCurrentEnvironment(),
            MembershipMemberType.USER,
            userDetails.getId());
    if (!userRoles.isEmpty()) {
        userRoles.forEach(role -> authorities.add(Maps.<String, String>builder().put("authority", role.getScope().toString() + ':' + role.getName()).build()));
    }
    userRoles = membershipService.getRoles(
            MembershipReferenceType.ORGANIZATION,
            GraviteeContext.getCurrentOrganization(),
            MembershipMemberType.USER,
            userDetails.getId());
    if (!userRoles.isEmpty()) {
        userRoles.forEach(role -> authorities.add(Maps.<String, String>builder().put("authority", role.getScope().toString() + ':' + role.getName()).build()));
    }

    // JWT signer
    Algorithm algorithm = Algorithm.HMAC256(environment.getProperty("jwt.secret"));

    Date issueAt = new Date();
    Instant expireAt = issueAt.toInstant().plus(Duration.ofSeconds(environment.getProperty("jwt.expire-after",
            Integer.class, DEFAULT_JWT_EXPIRE_AFTER)));

    final String token = JWT.create()
            .withIssuer(environment.getProperty("jwt.issuer", DEFAULT_JWT_ISSUER))
            .withIssuedAt(issueAt)
            .withExpiresAt(Date.from(expireAt))
            .withSubject(user.getId())
            .withClaim(JWTHelper.Claims.PERMISSIONS, authorities)
            .withClaim(JWTHelper.Claims.EMAIL, user.getEmail())
            .withClaim(JWTHelper.Claims.FIRSTNAME, user.getFirstname())
            .withClaim(JWTHelper.Claims.LASTNAME, user.getLastname())
            .withJWTId(UUID.randomUUID().toString())
            .sign(algorithm);

    final TokenEntity tokenEntity = new TokenEntity();
    tokenEntity.setType(BEARER);
    tokenEntity.setToken(token);

    if (state != null && !state.isEmpty()) {
        tokenEntity.setState(state);
    }

    final Cookie bearerCookie = cookieGenerator.generate(TokenAuthenticationFilter.AUTH_COOKIE_NAME, "Bearer%20" + token);
    servletResponse.addCookie(bearerCookie);

    return Response
            .ok(tokenEntity)
            .build();
}
 
Example 18
Source File: JWTAuthentication.java    From codeway_service with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 解析基础信息,返回解码后的JWT
 * @param jwtStr jwt
 * @return DecodedJWT
 */
private static DecodedJWT parse(String jwtStr) {
	Algorithm algorithm = null;
	try {
		algorithm = Algorithm.HMAC256(SECRET);
	} catch (IllegalArgumentException ex) {
		throw new RuntimeException(ex);
	}
	JWTVerifier verifier = JWT.require(algorithm).withIssuer(ISSUER).build();
	return verifier.verify(jwtStr);
}
 
Example 19
Source File: JwtUtil.java    From ShiroJwt with MIT License 4 votes vote down vote up
/**
 * 生成签名
 * @param account 帐号
 * @return java.lang.String 返回加密的Token
 * @author Wang926454
 * @date 2018/8/31 9:07
 */
public static String sign(String account, String currentTimeMillis) {
    try {
        // 帐号加JWT私钥加密
        String secret = account + Base64ConvertUtil.decode(encryptJWTKey);
        // 此处过期时间是以毫秒为单位,所以乘以1000
        Date date = new Date(System.currentTimeMillis() + Long.parseLong(accessTokenExpireTime) * 1000);
        Algorithm algorithm = Algorithm.HMAC256(secret);
        // 附带account帐号信息
        return JWT.create()
                .withClaim("account", account)
                .withClaim("currentTimeMillis", currentTimeMillis)
                .withExpiresAt(date)
                .sign(algorithm);
    } catch (UnsupportedEncodingException e) {
        logger.error("JWTToken加密出现UnsupportedEncodingException异常:{}", e.getMessage());
        throw new CustomException("JWTToken加密出现UnsupportedEncodingException异常:" + e.getMessage());
    }
}
 
Example 20
Source File: AccessTokenManager.java    From poc-graphql with MIT License 2 votes vote down vote up
/**
 * Verify the validity of a JWT token
 *
 * @param token JWT token
 * @throws Exception If token is not valid
 */
public void verifyToken(String token) throws Exception {
    Algorithm algorithm = Algorithm.HMAC256(businessDataRepository.loadCfgParam("ACCESS_TOKEN_SECRET"));
    JWTVerifier verifier = JWT.require(algorithm).withIssuer("AuthSystem").withAudience("poc").build();
    verifier.verify(token);
}