Created
February 24, 2021 11:26
-
-
Save rakshitshah94/3d1c6eb2cedeb5af6d9fd217e23ecbdd to your computer and use it in GitHub Desktop.
Easy way to generate jwt token and integrate it with your java or android project - beingcoders
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.crypto.spec.SecretKeySpec; | |
import javax.xml.bind.DatatypeConverter; | |
import java.security.Key; | |
import io.jsonwebtoken.*; | |
import java.util.Date; | |
//Sample method to construct a JWT | |
private String generateJWT(String id, String issuer, String subject, long ttlMillis) { | |
//The JWT signature algorithm we will be using to sign the token | |
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; | |
long nowMillis = System.currentTimeMillis(); | |
Date now = new Date(nowMillis); | |
//We will sign our JWT with our ApiKey secret | |
byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(apiKey.getSecret()); | |
Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); | |
//Let's set the JWT Claims | |
JwtBuilder builder = Jwts.builder().setId(id) | |
.setIssuedAt(now) | |
.setSubject(subject) | |
.setIssuer(issuer) | |
.signWith(signatureAlgorithm, signingKey); | |
//if it has been specified, let's add the expiration | |
if (ttlMillis >= 0) { | |
long expMillis = nowMillis + ttlMillis; | |
Date exp = new Date(expMillis); | |
builder.setExpiration(exp); | |
} | |
//Builds the JWT and serializes it to a compact, URL-safe string | |
return builder.compact(); | |
} |
@DavisNicholas04 , Yes you are absolutely right. If you are using Spring or Spring Boot, you can use @propertysource annotation to read your application configurations. Or you can simply retrieve it from your database tables.
Depending on your security level and project architecture - You can implement your own logic to retrieve the values!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello, this is really great and helpful. I was wondering what is meant by apikey.getSecret()
I don't see any variable listed named apiKey. Is this just a placeholder for "somehow read your .pem file for the secret/private key?"