【问题标题】:Creating token with JWT in JAVA [duplicate]在JAVA中使用JWT创建令牌[重复]
【发布时间】:2015-06-29 04:45:54
【问题描述】:

我必须使用 JWT 创建我的令牌,但我不知道该怎么做。

【问题讨论】:

  • 请在您的帖子中包含what you have tried。
  • 我正在使用这个 (jwt.io) 但我找不到有关创建令牌的一些信息。所以,我不知道这个库是否允许我创建令牌,或者我是否需要使用另一个库。所以我没有尝试任何东西,因为我不知道开始做。有人可以帮助我或指导我解决这个问题吗?谢谢

标签: java token jwt


【解决方案1】:

您必须为此使用库。 我个人使用nimbus-jose-jwt。 这是他们页面中使用 HS256 签署 JWT 的示例:

// Generate random 256-bit (32-byte) shared secret
SecureRandom random = new SecureRandom();
byte[] sharedSecret = new byte[32];
random.nextBytes(sharedSecret);

// Create HMAC signer
JWSSigner signer = new MACSigner(sharedSecret);

// Prepare JWT with claims set
JWTClaimsSet claimsSet = new JWTClaimsSet();
claimsSet.setSubject("alice");
claimsSet.setIssuer("https://c2id.com");
claimsSet.setExpirationTime(new Date(new Date().getTime() + 60 * 1000));

SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet);

// Apply the HMAC protection
signedJWT.sign(signer);

// Serialize to compact form, produces something like
// eyJhbGciOiJIUzI1NiJ9.SGVsbG8sIHdvcmxkIQ.onO9Ihudz3WkiauDO2Uhyuz0Y18UASXlSc1eS0NkWyA
String s = signedJWT.serialize();

您也可以使用jose4j。 他们页面中使用 RSA 签署 JWT(公钥 + 密钥)的示例: // 生成一个 RSA 密钥对,将用于 JWT 的签名和验证,包装在 JWK 中 RsaJsonWebKey rsaJsonWebKey = RsaJwkGenerator.generateJwk(2048);

// Give the JWK a Key ID (kid), which is just the polite thing to do
rsaJsonWebKey.setKeyId("k1");

// Create the Claims, which will be the content of the JWT
JwtClaims claims = new JwtClaims();
claims.setIssuer("Issuer");  // who creates the token and signs it
claims.setAudience("Audience"); // to whom the token is intended to be sent
claims.setExpirationTimeMinutesInTheFuture(10); // time when the token will expire (10 minutes from now)
claims.setGeneratedJwtId(); // a unique identifier for the token
claims.setIssuedAtToNow();  // when the token was issued/created (now)
claims.setNotBeforeMinutesInThePast(2); // time before which the token is not yet valid (2 minutes ago)
claims.setSubject("subject"); // the subject/principal is whom the token is about
claims.setClaim("email","mail@example.com"); // additional claims/attributes about the subject can be added
List<String> groups = Arrays.asList("group-one", "other-group", "group-three");
claims.setStringListClaim("groups", groups); // multi-valued claims work too and will end up as a JSON array

// A JWT is a JWS and/or a JWE with JSON claims as the payload.
// In this example it is a JWS so we create a JsonWebSignature object.
JsonWebSignature jws = new JsonWebSignature();

// The payload of the JWS is JSON content of the JWT Claims
jws.setPayload(claims.toJson());

// The JWT is signed using the private key
jws.setKey(rsaJsonWebKey.getPrivateKey());

// Set the Key ID (kid) header because it's just the polite thing to do.
// We only have one key in this example but a using a Key ID helps
// facilitate a smooth key rollover process
jws.setKeyIdHeaderValue(rsaJsonWebKey.getKeyId());

// Set the signature algorithm on the JWT/JWS that will integrity protect the claims
jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);

// Sign the JWS and produce the compact serialization or the complete JWT/JWS
// representation, which is a string consisting of three dot ('.') separated
// base64url-encoded parts in the form Header.Payload.Signature
// If you wanted to encrypt it, you can simply set this jwt as the payload
// of a JsonWebEncryption object and set the cty (Content Type) header to "jwt".
String jwt = jws.getCompactSerialization();

在 Erik Gillespie 指出的问题中,有更多选择。 jwt.io 页面允许您粘贴生成的令牌并查看他的有效负载。另外,如果您输入您的密钥,它会说明令牌的完整性。

【讨论】:

  • 第一个适用于我在 loraserver.io 中进行身份验证;)
【解决方案2】:

您可以使用以下方法:

public String jwtToken(String name) {
    long nowMillis = System.currentTimeMillis();
    Date now = new Date(nowMillis);

    Date expireDate = new Date(nowMillis);  

    Key key = MacProvider.generateKey();

    String compactJws = Jwts.builder()

           .setSubject(name)
            .setAudience("users")
           .setIssuedAt(now)
            .setExpiration(expireDate)
            .signWith(SignatureAlgorithm.HS512, key)
            .signWith(S)
            .compact();


    return compactJws;
}

【讨论】:

    【解决方案3】:

    尝试使用以下网址中提到的解决方案:
    https://dev.to/keysh/spring-security-with-jwt-3j76

    【讨论】:

      猜你喜欢
      • 2021-11-01
      • 1970-01-01
      • 2019-08-03
      • 2017-05-28
      • 2018-10-29
      • 2019-12-09
      • 1970-01-01
      • 2021-07-28
      • 1970-01-01
      相关资源
      最近更新 更多