Menu
- Generate Jwt Token With Key West
- Generate Jwt Secret Key
- Jwt Token Example
- C# Generate Jwt Token
- Generate Jwt Token With Key Card
- Generate Jwt Token Using Secret Key
You can authenticate as a GitHub App or as an installation.
Generating a private key. After you create a GitHub App, you'll need to generate one or more private keys. You'll use the private key to sign access token requests. You can create multiple private keys and rotate them to prevent downtime if a key is compromised or lost. To verify that a private key matches a public key, see Verifying private keys. The algorithm (HS256) used to sign the JWT means that the secret is a symmetric key that is known by both the sender and the receiver. It is negotiated and distributed out of band. Hence, if you're the intended recipient of the token, the sender should have provided you with the secret out of band.
Note: To access the API with your GitHub App, you must provide a custom media type in the
Accept
Header for your requests.application/vnd.github.machine-man-preview+json
Warning: The API may change without advance notice during the preview period. Preview features are not supported for production use. If you experience any issues, contact GitHub Support or GitHub Premium Support.
Generating a private key
After you create a GitHub App, you'll need to generate one or more private keys. You'll use the private key to sign access token requests.
You can create multiple private keys and rotate them to prevent downtime if a key is compromised or lost. To verify that a private key matches a public key, see Verifying private keys.
To generate a private key:
- In the upper-right corner of any page, click your profile photo, then click Settings.
- In the left sidebar, click Developer settings.
- In the left sidebar, click GitHub Apps.
- Select the GitHub App you want to modify.
- In 'Private keys,' click Generate a private key.
- You will see a private key in PEM format downloaded to your computer. Make sure to store this file because GitHub only stores the public portion of the key.
Note: If you're using a library that requires a specific file format, the PEM file you download will be in
PKCS#1 RSAPrivateKey
format.Verifying private keys
GitHub generates a fingerprint for each private and public key pair using a SHA-1 hash function. You can verify that your private key matches the public key stored on GitHub by generating the fingerprint of your private key and comparing it to the fingerprint shown on GitHub.
To verify a private key:
- Find the fingerprint for the private and public key pair you want to verify in the 'Private keys' section of your GitHub App's developer settings page. For more information, see Generating a private key.
- Generate the fingerprint of your private key (PEM) locally by using the following command.
- Compare the results of the locally generated fingerprint to the fingerprint you see in GitHub.
Deleting private keys
You can remove a lost or compromised private key by deleting it, but you must have at least one private key. When you only have one key, you will need to generate a new one before deleting the old one.
Authenticating as a GitHub App
Authenticating as a GitHub App lets you do a couple of things:
- You can retrieve high-level management information about your GitHub App.
- You can request access tokens for an installation of the app.
To authenticate as a GitHub App, generate a private key in PEM format and download it to your local machine. You'll use this key to sign a JSON Web Token (JWT) and encode it using the
RS256
algorithm. GitHub checks that the request is authenticated by verifying the token with the app's stored public key.Here's a quick Ruby script you can use to generate a JWT. Note you'll have to run
gem install jwt
before using it.YOUR_PATH_TO_PEM
and YOUR_APP_ID
are the values you must replace.Use your GitHub App's identifier (
YOUR_APP_ID
) as the value for the JWT iss (issuer) claim. You can obtain the GitHub App identifier via the initial webhook ping after creating the app, or at any time from the app settings page in the GitHub.com UI.After creating the JWT, set it in the
Header
of the API request:YOUR_JWT
is the value you must replace.The example above uses the maximum expiration time of 10 minutes, after which the API will start returning a
401
error:You'll need to create a new JWT after the time expires.
Accessing API endpoints as a GitHub App
For a list of REST API v3 endpoints you can use to get high-level information about a GitHub App, see 'GitHub Apps.'
Authenticating as an installation
Authenticating as an installation lets you perform actions in the API for that installation. Before authenticating as an installation, you must create an installation access token. These installation access tokens are used by GitHub Apps to authenticate.
By default, installation access tokens are scoped to all the repositories that an installation can access. You can limit the scope of the installation access token to specific repositories by using the
repository_ids
parameter. See the Create a new installation token endpoint for more details. Installation access tokens have the permissions configured by the GitHub App and expire after one hour.To create an installation access token, include the JWT generated above in the Authorization header in the API request:
The response will include your installation access token:
To authenticate with an installation access token, include it in the Authorization header in the API request:
YOUR_INSTALLATION_ACCESS_TOKEN
is the value you must replace.Accessing API endpoints as an installation
For a list of REST API v3 endpoints that are available for use by GitHub Apps using an installation access token, see 'Available Endpoints.'
For a list of endpoints related to installations, see 'Installations.'
HTTP-based Git access by an installation
Installations with permissions on
contents
of a repository, can use their installation access tokens to authenticate for Git access. Use the installation access token as the HTTP password:Java support for JWT (JSON Web Tokens) used to require a lot of work: extensive customization, hours lost resolving dependencies, and pages of code just to assemble a simple JWT. Not anymore!
This tutorial will show you how to use an existing JWT library to do two things:
- Generate a JWT
- Decode and verify a JWT
You’ll notice the tutorial is pretty short. That’s because it’s that easy. If you’d like to dig deeper, take a look at the JWT Spec or dive into this longer post about using JWTs for token authentication in Spring Boot apps.
What are JWTs?
JSON Web Tokens are JSON objects used to send information between parties in a compact and secure manner. The JSON spec, or Javascript Object Notation, defines a way of creating plain text objects using key value pairs. It’s a compact way of structuring data built upon primitive types (numbers, strings, etc…). You’re probably already pretty familiar with JSON. It’s like XML without all the brackets.
Generate Jwt Token With Key West
Tokens can be used to send arbitrary state between parties. Often here “parties” means a client web application and a server. JWTs have many uses: authentication mechanism, url-safe encoding, securely sharing private data, interoperability, data expiration, etc.
In practice, this information is often about two things: authorization and session state. JWTs can be used by a server to tell the client app what actions the user is allowed to execute (or what data they are allowed to access).
JWTs are often also used to store state-dependent user data for a web session. Because the JWT is passed back and forth between the client app and the server, it means that state data does not have to be stored in a database somewhere (and subsequently retrieved on every request); because of this, it scales well.
Let’s take a look at an example JWT (taken from jsonwebtoken.io)
JWTs have three parts: a header, a body, and a signature. The header contains info on how the JWT is encoded. The body is the meat of the token (where the claims live). The signature provides the security.
There’s a lot of detail we’re not going to go into here regarding how tokens are encoded and how information is stored in the body. Check out the previously mentioned tutorial if you want.
Don’t forget: cryptographic signatures do not provide confidentiality; they are simply a way of detecting tampering with a JWT, and unless a JWT is specifically encrypted, they are publicly visible. The signature simply provides a secure way of verifying the contents.
Great. Got it? Now you need to make a token with JJWT!For this tutorial, we’re using an existing JWT library. Java JWT (a.k.a., JJWT) was created by Les Hazlewood (lead committer to Apache Shiro, former co-founder and CTO at Stormpath, and currently Okta’s very own Senior Architect), JJWT is a Java library that simplifies JWT creation and verification. It is based exclusively on the JWT, JWS, JWE, JWK and JWA RFC specifications and open source under the terms of the Apache 2.0 License. The library also adds some nice features to the spec, such as JWT compression and claims enforcement.
Generate a Token in Java
This parts super easy. Let’s look at some code. Clone the GitHub repo:
This example is pretty basic, and contains a
src/main/java/JWTDemo.java
class file with two static methods: createJWT()
and decodeJWT()
. Cunningly enough, these two methods create a JWT and decode a JWT. Take a look at the first method below.To summarize, the
createJWT()
method does the following:- Sets the hashing algorithm
- Gets the current date for the Issued At claim
- Uses the SECRET_KEY static property to generate the signing key
- Uses the fluent API to add the claims and sign the JWT
- Sets the expiration date
This could be customized to your needs. If, for example, you wanted to add different or custom claims.
Generate Jwt Secret Key
Decode a Token
Now take a look at the even simpler
decodeJWT()
method.The method again uses the static
SECRET_KEY
property to generate the signing key, and uses that to verify that the JWT has not been tampered with. The method will throw io.jsonwebtoken.SignatureException
exception if the signature does not match the token. If the signature does match, the method returns the claims as a Claims
object.That’s pretty much it!
Jwt Token Example
Run the JUnit Tests
For extra credit, you can run the JUnit tests in the example project. There are three tests, and they demonstrate some basic features on the JJWT library. The first test shows the happy path, creating and successfully decoding a valid JWT. The second test shows how the JJWT library will fail when you attempt to decode a totally bogus string as a JWT. The last test shows how a tampered-with JJWT will cause the
decodeJWT()
method to throw a SignatureException
.You can run these tests from the command line using:
The
-i
is to set Gradle’s log level to Info
so that we see the simple logging output from the tests.Learn More About Working with JWTs in Your Java Apps
The JJWT library makes it super easy to create and verify JWTs. Just specify a secret key and some claims, and you’ve got a JJWT. Later, use the same secret key to decode the JJWT and verify its contents.
Creating and using JJWTs is now so easy, why aren’t you using them?
Don’t forget SSL! Remember that unless JWTs are encrypted, the information encoded within them is generally only Base64 encoded, which any small child and some pets can read. So unless you want China, Russia, and the FBI reading all of your session data, encrypt it using SSL.
Baeldung has a pretty good in depth tutorial on Java and JWTs.
C# Generate Jwt Token
Also, here are some more links from the Okta blog to keep you going:
Generate Jwt Token With Key Card
If you have any questions about this post, please add a comment below. For more awesome content, follow @oktadev on Twitter, like us on Facebook, or subscribe to our YouTube channel.
Generate Jwt Token Using Secret Key
Please enable JavaScript to view the comments powered by Disqus.