cotter-token-js
TypeScript icon, indicating that this package has built-in type declarations

0.1.11 • Public • Published

cotter-token-js

npm version

Cotter Helper to Validate Responses and JWT Tokens for JavaScript

Validate Cotter's Identity and Event responses, read and decode jwt tokens generated by Cotter using the classes defined here. To read more about Cotter, get started with our 📚 integration guides and example projects.

Install

npm install cotter-token-js --save

or

yarn add cotter-token-js

Usage

To decode a jwt token:

import { CotterJwtToken } from "cotter-token-js";

const decodedToken = new CotterJwtToken(token);

console.log(decodedToken.payload); // decoded jwt token object

console.log(decodedToken.token); // original token string

Expiry, IssuedAt, and Audience

// getting payload.exp
const expiredAt = decodedToken.getExpiration();

// getting payload.iat
const issuedAt = decodedToken.getIssuedAt();

// getting payload.aud
const audience = decodedToken.getAudience();

Usage with Cotter

Cotter returns 2 types of jwt token, CotterAccessToken and CotterIDToken.

CotterAccessToken

This access token should be passed to your backend server, and used to authorize users to access your API. Validate the access token passed to your backend server using this example.

To decode a the access token:

import { CotterAccessToken } from "cotter-token-js";

const decodedToken = new CotterAccessToken(accessToken);

console.log(decodedToken.payload); // decoded jwt token object

console.log(decodedToken.token); // original token string

CotterAccessToken have the following attributes

class CotterAccessToken {
  token: string; // This is the original token string
  payload: {
    client_user_id: string;
    authentication_method: string;
    type: string;
    scope: string;
    identifier: string;

    // standard claims
    aud: string;
    exp: number;
    jti: string;
    iat: number;
    iss: string;
    nbf: number;
    sub: string; // Cotter User ID
  }
  
  getAuthMethod(): string   // Get Authentication method (OTP/MAGIC_LINK/TRUSTED_DEVICE/WEBAUTHN)
  getScope(): string        // Get Scope
  getID(): string           // Get Cotter User ID
  getIdentifier(): string   // Get user's identifier (email/phone/username)
  getClientUserID(): string // DEPRECATED: Get client_user_id
}

CotterAccessToken also extends all the methods available for CotterJWTToken.

CotterIDToken

The ID token is following OpenID specifications, and is provided to get more information about the user.

To decode a the id token:

import { CotterIDToken } from "cotter-token-js";

const decodedToken = new CotterIDToken(accessToken);

console.log(decodedToken.payload); // decoded jwt token object

console.log(decodedToken.token); // original token string

CotterIDToken have the following attributes

class CotterIDToken {
  token: string; // This is the original token string
  payload: {
    client_user_id: string;
    auth_time: string;      // authentication time
    identifier: string;     // User's email/phone/username
    type: string;           
    
    // standard claims
    aud: string;
    exp: number;
    jti: string;
    iat: number;
    iss: string;
    nbf: number;
    sub: string; // Cotter User ID
  }
  
  getAuthTime(): string     // Get authentication time
  getIdentifier(): string   // Get user's identifier (email/phone/username)
  getID(): string           // Get Cotter User ID
  getClientUserID(): string // DEPRECATED: Get client_user_id
}

CotterIDToken also extends all the methods available for CotterJWTToken.

Getting Access Token from Cotter

When you want to request access tokens from cotter, add a query paramater ?oauth_token=true at the end of your request.

For reference, current base url for Cotter:


https://www.cotter.app/api/v0

There are several endpoints where you can request access tokens from:

1. Create User Endpoint

POST /user/create?oauth_token=true

2. Update Methods Endpoint

PUT /user/:client_user_id?oauth_token=true

3. Create Approved Event Request Endpoint

POST /event/create?oauth_token=true

4. Get Event Request Endpoint

GET /event/get/:event_id?oauth_token=true

5. Get Identity Endpoint (using PKCE flow)

GET /verify/get_identity?oauth_token=true

When using these endpoints, you'll get an additional field called oauth_token:

Response

{
  ...
  "oauth_token": {
    "access_token": "eyJhbGciOiJFUzI1sInR5cC...",
    "auth_method": "TRUSTED_DEVICE",
    "expires_in": 3600,
    "id_token": "eyJhbGciOiJFUz...",
    "refresh_token": "60:79hbLxl3aTjWWgCcIRnn...",
    "token_type": "Bearer"
  }
}

Get Token using Refresh Token

When your access token expires, you can get a new one using the refresh token that was given.

POST /token
Content-Type: application/json
API_KEY_ID: <API-KEY-ID>


{
  "grant_type": "refresh_token",
  "refresh_token": "3:8xhGfVzGa91WOZ1eDk..."
}

Response

Note that you don't get a refresh token back.

{
  "access_token": "eyJhbGciOsInR5cCI6...",
  "auth_method": "OTP",
  "expires_in": 3600,
  "id_token": "eyJhbGciOiJFUzI1NiI...",
  "token_type": "Bearer"
}

Validating JWT Token

To validate the access or identity token, you can use Cotter's package cotter-node

import { CotterValidateJWT } from "cotter-node";

try {
  var valid = await CotterValidateJWT(token);
} catch (e) {
  console.log(e);
}

If you can't use the package above

To validate the jwt token, you need Cotter's JWT Public Key. The Public Key is specified in this endpoint:

GET /token/jwks

There's only one key for now, so use that key.

To Validate jwt token using this key, check the example

A simple example to validate the jwt token:

var jwt = require("jsonwebtoken");
var jwkToPem = require("jwk-to-pem");
var axios = require("axios");

const validateToken = async (token) => {
  const publicKeys = await axios.default.get(
    "https://www.cotter.app/api/v0/token/jwks"
  );
  const jwk = publicKeys.data.keys[0];
  const pem = jwkToPem(jwk);
  jwt.verify(token, pem, { algorithms: ["ES256"] }, function (err, decodedToken) {
    console.log(err);
    console.log(decodedToken);
  });
}

validateToken(accessToken); // 👈 pass in access token here

Package Sidebar

Install

npm i cotter-token-js

Weekly Downloads

53

Version

0.1.11

License

ISC

Unpacked Size

16.9 kB

Total Files

18

Last publish

Collaborators

  • putrikarunia
  • albertputrapurnama
  • julianna-stytch