Cotter
  • 🚀Getting Started
  • Features & Concepts
    • 💬Sign In with Email/Phone Number
    • 🔐Sign In with Device
      • How it works
    • 🧬Sign In with WebAuthn
  • 📌Quickstart Guides
    • All Guides & Tutorials
    • HTML – Sign in with Email/Phone
    • React – Sign in with Email/Phone
    • React – WebAuthn
    • ▲ Next.js
    • Angular
    • Webflow
    • Bubble.io
    • Python SDK for a CLI
    • React Native – Sign in with Device
    • iOS – Sign in with Device
    • Flutter – Sign in with Device
  • 📘SDK Reference
    • Web
      • Sign In with Email/Phone Number
        • Customize the Form
        • Checking the email or phone before sending a verification code
        • Sending Code or Link via WhatsApp
        • Styling
        • Older SDK
          • Customize the Form
      • Sign in with Social Login
        • Getting Access Tokens from Social Login Providers
        • Github Instructions
        • Google Instructions
      • Sign In with WebAuthn
        • Register WebAuthn for a logged-in user
      • Sign In with Device
        • Steps for Pop Up Authentication Prompt
        • Advanced Customization for Login Form
        • Advanced Customization for Pop Up Authentication Prompt
      • Getting Access Token and Logged-In User Info
      • Sending Successful Form Submission
      • FAQ & Troubleshooting
    • React Native
      • Installation
      • Sign In with Device
        • Add Email/Phone Verification
        • Authenticate from a Non-Trusted Device
        • Add a new Trusted Device
        • Remove Trusted Device
      • Sign In with Email/Phone Number
      • Getting Stored OAuth Tokens and User Information
      • FAQ
      • Older SDK Versions
        • Sign in with Email/Phone
        • Sending Code via WhatsApp
        • Sign In with Device
          • Authenticate from a Non-Trusted Device
          • Add a new Trusted Device
          • Customization
    • Flutter
      • Sign In with Device
        • Add Email/Phone Verification
        • Authenticate from a Non-Trusted Device
      • Sign in with Email/Phone Number
      • Getting the Logged-in User
      • Getting OAuth Tokens
      • Signing a User Out
    • iOS
      • Sign In with Email/Phone Number
      • Sign In with Device
        • Authenticate from a Non-Trusted Device
        • Push Notification
        • Check if Trusted Device is Enrolled
        • Add a New Trusted Device
        • Remove Trusted Device
      • Older Versions
        • Biometric/Pin
    • Android
      • Sign In with Device
        • Authenticate from a Non-Trusted Device
        • Check if Trusted Device is Enrolled
        • Add a new Trusted Device
        • Remove Trusted Device
        • Customization
      • Sign In with Email/Phone Number
      • Biometric/Pin
        • Advanced Methods
        • Customization
        • Setting Strings
        • Styling
      • Older SDK Version
        • Sign In with Device
          • Authenticate from a Non-Trusted Device
    • Python (for CLI)
    • API for Other Mobile Apps or CLI
      • Verify Email/Phone Number
        • Handling URL Scheme
    • Backend: Handling Response
  • 🛡️ Protecting Your Account
    • Only Allow Your Website/App to Use Your API Key
    • Rate Limit
    • Enable reCAPTCHA to Protect Against Automated Abuse
  • 🗝️ Getting Access Token
    • Cotter's OAuth 2.0 Tokens Specification
    • Getting the Tokens
      • Get Tokens during Authentication
      • Using the Refresh Token
    • Storing and Removing Tokens
    • Renewing Expired Tokens
    • Verifying JWT Tokens
    • Requesting Custom Fields on your JWT Token
    • Older API
      • Using HTTP Requests
      • Getting the Tokens
        • During Authentication
          • During Email/Phone Verification
        • During enrolling Trusted Devices
  • 🔌API Reference
    • User API
      • User Object
    • OAuth Tokens API
      • Verify JWT Token using API (serverless)
      • Requesting Custom Claims on your Access Token
      • Older API
    • OAuth Tokens from Social Login
    • Event Object
    • Reset PIN API
  • Older API
    • Validating Cotter's Identity Token
    • Validating Cotter's Event Response
Powered by GitBook
On this page
  • Register or Login your user to your Database
  • Validating Cotter's Access Token
  1. SDK Reference

Backend: Handling Response

Register or Login your user to your Database

When the user is authenticated, you will receive a response similar to this from your front end. Your frontend is reponsible for sending this payload to your server.

{
    "email": "myemail@gmail.com", // User's email (or phone number)
    "oauth_token": {
        "access_token": "eyJhbGciOiJFUzI1NiIsImt...", // Access Token to validate
        "id_token": "eyJhbGciOiJFUzI1Ni...",
        "refresh_token": "27805:CNf76faa8trMhjXM...",
        "expires_in": 3600,
        "token_type": "Bearer",
        "auth_method": "OTP"
    },
    "user": {
        "ID": "abcdefgh-abcd-abcd-abcd-af6f81fb5432", // Cotter User ID
        "created_at": "2020-07-21T05:50:14.182738Z",
        "updated_at": "2020-07-21T06:00:47.115096Z",
        "deleted_at": "0001-01-01T00:00:00Z",
        "issuer": "<YOUR_API_KEY_ID>",
        "identifier": "putrikarunian@gmail.com"
    }
}

Send this payload to your backend to register or login the user in your database. A typical flow would look like this:

  1. Validate the access token

  2. Check if the email exists in your database

    • If it doesn't exists: Create a new user

    • If it exists: Continue login

  3. (Optional) If you want to use your own session tokens, set the cookie here after validating the access token.

  4. (Optional) if you want to use Cotter's tokens, either store Cotter's access token in the cookie or on the front-end side.

Examples:

const express = require("express");
const app = express();
var cors = require("cors");
var bodyParser = require("body-parser");
var cotterNode = require("cotter-node");
var cotterToken = require("cotter-token-js");
var session = require("express-session");
const port = 3005;
app.use(cors());
app.use(bodyParser.json());


// EXAMPLE LOGIN ENDPOINT
app.post("/login", async (req, res) => {
  console.log(req.body);

  // Validate access token
  const access_token = req.body.oauth_token.access_token;
  var valid = false;
  try {
    valid = await cotterNode.CotterValidateJWT(access_token);
  } catch (e) {
    valid = false;
  }
  if (!valid) {
    res.status(403).end("Invalid access token");
    return;
  }

  // (Optional) Read access token
  let decoded = new cotterToken.CotterAccessToken(access_token);
  console.log(decoded);
    
  // (Optional) Register or Login User

  // (Optional) Set access token as cookie

  res.status(200).json(decoded.payload).end();
});

app.listen(port, () =>
  console.log(`Example app listening at http://localhost:${port}`)
);
from flask import Flask
from flask import request
from flask_cors import CORS
import requests
from jose import jwt

CotterJWKSURL="https://www.cotter.app/api/v0/token/jwks"

app = Flask(__name__)
CORS(app)


@app.route('/login', methods=['POST'])
def login(name=None):
    req = request.get_json();

    # Getting jwt key
    r = requests.get(url = CotterJWKSURL);
    data = r.json();
    print(data);
    public_key = data["keys"][0];

    # Getting access token and validate it
    token = req["oauth_token"]["access_token"]
    resp = jwt.decode(token, public_key, algorithms='ES256', audience=API_KEY_ID)
    
    # User Authenticated!
    # 1) If user doesn't exist, register user to db. Otherwise, continue
    # 2) Either use Cotter's Access Token for your entire API authorization
    #    OR
    #    You can Generate your JWT Tokens or other session management here
    
    return resp;

Validating Cotter's Access Token

Read more on how to verify the OAuth Tokens from Cotter here:

PreviousHandling URL SchemeNextOnly Allow Your Website/App to Use Your API Key

Last updated 4 years ago

📘
Verifying JWT Tokens