rn-jwt
v2.0.9
Published
React Native JWT implementation with full algorithm support
Downloads
84
Readme
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.ipevRNuRP6HflG8cFKnmUPtypruRC4fb1DWtoLL62SYEach 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: "[email protected]",
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: "[email protected]",
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: "[email protected]",
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: '[email protected]',
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 usedtyp(Type) - Optional. Defaults to "JWT" if not specifiedcty(Content Type) - Optional. Content type of the JWTkid(Key ID) - Optional. Identifier for the key used to sign the JWTjku(JWK Set URL) - Optional. URL pointing to JWK Set containing the keyjwk(JSON Web Key) - Optional. The key used to sign the JWTx5u(X.509 URL) - Optional. URL pointing to X.509 certificate chainx5c(X.509 Certificate Chain) - Optional. X.509 certificate chainx5t(X.509 Certificate SHA-1 Thumbprint) - Optionalx5t#S256(X.509 Certificate SHA-256 Thumbprint) - Optionalcrit(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
endFeel free to colaborate with the project!
