Skip to content

Instantly share code, notes, and snippets.

@bdemers
Created October 11, 2019 17:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bdemers/1e2713df2857bc0f35b81dc2ccd0ae9e to your computer and use it in GitHub Desktop.
Save bdemers/1e2713df2857bc0f35b81dc2ccd0ae9e to your computer and use it in GitHub Desktop.
Create and Parse JWTs in Java with JJWT
package com.okta.developer;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Base64;
import java.util.Date;
import java.util.Random;
public class AppExample {
public static void main(String[] args) {
Instant now = Instant.now();
// don't forget to generate a different secret!
byte[] secret = Base64.getDecoder().decode("o4OdCNjd8mmDN2+/nfHdIB2ZWta80foXqDx2rouL4nw=");
String jwt = Jwts.builder()
.setSubject("Brian Demers")
.setAudience("video demo")
.claim("1d20", new Random().nextInt(20) +1)
.setIssuedAt(Date.from(now))
.setExpiration(Date.from(now.minus(1, ChronoUnit.MINUTES)))
.signWith(Keys.hmacShaKeyFor(secret))
.compact();
System.out.println(jwt);
Jws<Claims> result = Jwts.parser()
.requireAudience("video demo")
.setAllowedClockSkewSeconds(62)
.setSigningKey(Keys.hmacShaKeyFor(secret))
.parseClaimsJws(jwt);
System.out.println(result);
System.out.println("1d20: "+ result.getBody().get("1d20", Integer.class));
}
}
@rohangedam
Copy link

rohangedam commented May 25, 2021

I need a code for client id, secret, redirect url, so that where we can pass parameters

@bdemers
Copy link
Author

bdemers commented May 25, 2021

Hey @rohangdam,

It sounds like you might be confusing this example for an OIDC / OAuth 2.0 Authorization Code Flow example (i.e. a standard OAuth redirect)?

I can probably point you to a blog post that would help, just let me know what frameworks your application is built on.

@averma111
Copy link

Hi,

I have a similar requirement for "I need a code for client id, secret, redirect url, so that where we can pass parameters" for SSO based JWT authentication.

@averma111
Copy link

The application is based on pure java no framework involved. I am basically trying to write a plugin for Apache Druid SSO based Authentication.

@bdemers
Copy link
Author

bdemers commented Jul 6, 2021

Hi @averma111,

"SSO based JWT authentication" probably isn't what you want (and might be making it harder to search for solutions).
You probably want to search for "OIDC or OAuth 2.0 Authorization Code Flow", (which is where the client id/secret and redirect come in).

You can probably setup Pac4j with Druid

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment