Socket
Book a DemoInstallSign in
Socket

rn-jwt

Package Overview
Dependencies
Maintainers
1
Versions
11
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

rn-jwt

React Native JWT implementation with full algorithm support

2.0.9
latest
Source
npmnpm
Version published
Weekly downloads
18
Maintainers
1
Weekly downloads
 
Created
Source

rn-jwt

A React Native library that uses native modules to work with JWTs!

rn-jwt is a library that implements the power of JWTs inside React Native! It's goal is to sign, verify and decode JSON web tokens in order to provide a secure way to transmit authentic messages between two parties.

The difference to another libraries is that rn-jwt relies on the native realm in order to do JWT-related operations instead of the Javascript realm, so it's more stable (and works without hacks!).

Supported algorithms: HS256, HS384, HS512, RS256, RS384, RS512, ES256, ES384, ES512, PS256, PS384, PS512

React Native version required: >= 0.46.0

What's a JSON Web Token?

Don't know what a JSON Web Token is? Read on. Otherwise, jump down to the Installation section.

JWT is a means of transmitting information between two parties in a compact, verifiable form.

The bits of information encoded in the body of a JWT are called claims. The expanded form of the JWT is in a JSON format, so each claim is a key in the JSON object.

The compacted representation of a signed JWT is a string that has three parts, each separated by a .:

eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJKb2UifQ.ipevRNuRP6HflG8cFKnmUPtypruRC4fb1DWtoLL62SY

Each section is base 64 encoded. The first section is the header, which at a minimum needs to specify the algorithm used to sign the JWT. The second section is the body. This section has all the claims of this JWT encoded in it. The final section is the signature. It's computed by passing a combination of the header and body through the algorithm specified in the header.

If you pass the first two sections through a base 64 decoder, you'll get the following (formatting added for clarity):

header

{
  "alg": "HS256"
}

body

{
  "sub": "Joe"
}

In this case, the information we have is that the HMAC using SHA-256 algorithm was used to sign the JWT. And, the body has a single claim, sub with value Joe.

There are a number of standard claims, called Registered Claims, in the specification and sub (for subject) is one of them.

To compute the signature, you must know the secret that was used to sign it. In this case, it was the word secret. You can see the signature creation is action here (Note: Trailing = are lopped off the signature for the JWT).

Now you know (just about) all you need to know about JWTs. (Credits: jwtk/jjwt)

Installation

Install the package with: yarn add rn-jwt

If your React Native version supports autolinking, you should only run pod install on ios folder and you'll be good to go.

If not...

react-native link rn-jwt

The linking process on the iOS version works with Cocoapods

Manual Android linking

  • in android/app/build.gradle:
dependencies {
    ...
    compile "com.facebook.react:react-native:+"  // From node_modules
+   compile project(':rn-jwt')
}
  • in android/settings.gradle:
...
include ':app'
+ include ':rn-jwt'
+ project(':rn-jwt').projectDir = new File(rootProject.projectDir, '../node_modules/rn-jwt/android')
  • in MainApplication.java:
+ import com.monokaijs.rnjwt.RNJwtPackage;

  public class MainApplication extends Application implements ReactApplication {
    //......

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
+         new RNJwtPackage(),
          new MainReactPackage()
      );
    }

    ......
  }

Manual iOS linking

You need to use Cocoapods at the moment. Open your Podfile and insert the following line in your main target:

pod 'rn-jwt', :podspec => '../node_modules/rn-jwt/rn-jwt.podspec'

Then run pod install and open your .xcworkspace

Usage

  • sign:
import { sign } from "rn-jwt";

// HMAC algorithms (HS256, HS384, HS512) - use string secret
sign(
  {
    iss: "luisfelipez@live.com",
    exp: new Date().getTime() + 3600 * 1000, // expiration date, required, in ms, absolute to 1/1/1970
    additional: "payload"
  }, // body
  "my-secret", // string secret
  {
    alg: "HS256",
    headers: {
      kid: "key-id-123", // Key ID
      typ: "JWT", // Token type (optional, defaults to "JWT")
      custom: "value" // Custom header parameters
    }
  }
)
  .then(console.log) // token as the only argument
  .catch(console.error); // possible errors

// RSA algorithms (RS256, RS384, RS512) - use PEM-encoded private key
const privateKeyPEM = `-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC...
-----END PRIVATE KEY-----`;

sign(
  {
    iss: "luisfelipez@live.com",
    exp: new Date().getTime() + 3600 * 1000,
    additional: "payload"
  },
  privateKeyPEM, // PEM-encoded private key
  {
    alg: "RS256",
    headers: {
      kid: "rsa-key-1", // Key ID for key rotation
      x5t: "dGhpcyBpcyBhIFNIQTEgdGVzdA", // X.509 certificate thumbprint
      jku: "https://example.com/.well-known/jwks.json" // JWK Set URL
    }
  }
)
  .then(console.log)
  .catch(console.error);

// ECDSA algorithms (ES256, ES384, ES512) - use PEM-encoded EC private key
const ecPrivateKeyPEM = `-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg...
-----END PRIVATE KEY-----`;

sign(
  {
    iss: "luisfelipez@live.com",
    exp: new Date().getTime() + 3600 * 1000,
    additional: "payload"
  },
  ecPrivateKeyPEM, // PEM-encoded EC private key
  {
    alg: "ES256",
    headers: {
      kid: "ec-key-1", // Key ID for ECDSA key
      crit: ["kid"], // Critical header parameters that must be understood
      custom_claim: "custom_value" // Custom header parameters
    }
  }
)
  .then(console.log)
  .catch(console.error);
  • decode:
import { decode } from "rn-jwt";

// HMAC algorithms - use string secret
decode(
  token, // the token
  "my-secret", // string secret
  {
    alg: "HS256", // specify algorithm for verification
    skipValidation: true // to skip signature and exp verification
  }
)
  .then(console.log) // already an object. read below, exp key note
  .catch(console.error);

// RSA algorithms - use PEM-encoded public key
const publicKeyPEM = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu1SU1LfVLPHCozMxH2Mo...
-----END PUBLIC KEY-----`;

decode(
  token,
  publicKeyPEM, // PEM-encoded public key
  {
    alg: "RS256"
  }
)
  .then(console.log)
  .catch(console.error);

// ECDSA algorithms - use PEM-encoded EC public key
const ecPublicKeyPEM = `-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...
-----END PUBLIC KEY-----`;

decode(
  token,
  ecPublicKeyPEM, // PEM-encoded EC public key
  {
    alg: "ES256"
  }
)
  .then(console.log)
  .catch(console.error);

/*
  response example:
  {
    headers: {
      alg: 'HS256'
    },
    payload: {
      iss: 'luisfelipez@live.com',
      exp: 'some date', // IN SECONDS
    }
  }
*/

JWT Headers

The library supports all standard JWT header parameters as defined in RFC 7515 and RFC 7517:

Standard Header Parameters

  • alg (Algorithm) - Required. Automatically set based on the algorithm used
  • typ (Type) - Optional. Defaults to "JWT" if not specified
  • cty (Content Type) - Optional. Content type of the JWT
  • kid (Key ID) - Optional. Identifier for the key used to sign the JWT
  • jku (JWK Set URL) - Optional. URL pointing to JWK Set containing the key
  • jwk (JSON Web Key) - Optional. The key used to sign the JWT
  • x5u (X.509 URL) - Optional. URL pointing to X.509 certificate chain
  • x5c (X.509 Certificate Chain) - Optional. X.509 certificate chain
  • x5t (X.509 Certificate SHA-1 Thumbprint) - Optional
  • x5t#S256 (X.509 Certificate SHA-256 Thumbprint) - Optional
  • crit (Critical) - Optional. Array of header parameter names that must be understood

Custom Headers

You can also include custom header parameters for application-specific needs:

sign(payload, secret, {
  alg: "HS256",
  headers: {
    kid: "key-rotation-id",
    iss: "token-issuer", // Custom issuer in header
    custom_param: "custom_value",
    version: "1.0"
  }
})

Header Usage Examples

Key Rotation with Key ID:

{
  alg: "RS256",
  headers: {
    kid: "2023-key-1" // Helps identify which key to use for verification
  }
}

Certificate Chain:

{
  alg: "RS256",
  headers: {
    x5c: ["MIIC...", "MIIB..."], // X.509 certificate chain
    x5t: "dGhpcyBpcyBhIFNIQTEgdGVzdA" // Certificate thumbprint
  }
}

Critical Parameters:

{
  alg: "ES256",
  headers: {
    kid: "critical-key-id",
    crit: ["kid"] // Indicates that 'kid' parameter is critical and must be understood
  }
}

Troubleshooting

haste collision. react-native/package.json collides with Pods/React/package.json

Add this to your Podfile:

post_install do |installer|
  installer.pods_project.targets.each do |target|
    if target.name == "React"
      target.remove_from_project
    end
  end
end

Feel free to colaborate with the project!

FAQs

Package last updated on 16 Jul 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

About

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.

  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc

U.S. Patent No. 12,346,443 & 12,314,394. Other pending.