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
  • Overview
  • What you're building
  • Steps
  • Step 1. Installation
  • Step 2. Set allowed Authentication Methods in the Developer Dashboard
  • Step 3. Initializing Cotter
  • Step 4. Creating a User
  • Step 5. Enroll PIN or Biometric
  • Step 6. Verify PIN and/or Biometrics on an action
  • 🎉 You're done!
  • Additional Notes
  • The Callbacks
  • 1. HTTP Callbacks
  • 2. Authentication Callbacks
  1. SDK Reference
  2. iOS
  3. Older Versions

Biometric/Pin

Cotter's iOS SDK helps you easily add a Biometric prompt or PIN fallback to your app. This is useful for protecting transactions or sensitive information like medical records.

PreviousOlder VersionsNextAndroid

Last updated 5 years ago

Overview

Enabling PIN and Biometric using Cotter's Android SDK consists of:

  1. Initializing Cotter

  2. Calling functions to start PIN and Biometric Enrollment

  3. Verify Biometric or PIN before an action

  4. Enabling and disabling Biometric or PIN in Settings

What you're building

Steps

Step 1. Installation

We use Cocoapods as our SDK host. If you're using Cocoapods, add this to your Podfile

pod 'Cotter'

Then simply run pod install

Step 2. Set allowed Authentication Methods in the Developer Dashboard

Remember to select the correct project in the dropdown list

Step 3. Initializing Cotter

You will have to do import Cotter on the file that will use Cotter. Then do initialization as follows

import Cotter...let cotter = Cotter(
 apiSecretKey: <your-api-secret-key>,
 apiKeyID: <your-api-key-id>,
 cotterURL: "https://www.cotter.app/api/v0",
 userID: <your-user-id>, // user’s id that will be created later
 configuration: <your-cotter-config>
)

example:

import Cotter...let cotter = Cotter(
 apiSecretKey: "<API_SECRET_KEY>",
 apiKeyID: "<API_KEY_ID>",
 cotterURL: "https://www.cotter.app/api/v0",
 userID: "hello@example.com",
 configuration: [:]
 );

Step 4. Creating a User

1. Registering a new User

/* https://www.cotter.app/api/v0/user/create */
CotterAPIService.shared.registerUser(
  userID: <your-user-id>,
  cb: { response in
    // handle Result (Swift 5 enum) callback here
  }
)

Response:

{
  "ID": "9449e9e9-00e0-4d6b-a4b6-28c5b22b0b0f",
  "created_at": "2020-01-21T12:40:21.200727668Z",
  "update_at": "2020-01-21T12:40:21.200727668Z",
  "deleted_at": null,
  "issuer": "<your key ID>",
  "client_user_id": "<Your User Identifier (string)>",
  "enrolled": [],
  "default_method": null
}

Example:

// registerUserCb is a simple callback that handles the cases for 
// the API Call
func registerUserCb(_ response: CotterResult<CotterUser>){
    switch response{
    case .success(let user):
        print("successfully registered the \(user)")

    case .failure(let err):
        // you can put exhaustive error handling here
        switch err{
        case CotterAPIError.decoding:
            print("this is decoding error on registering user")
            break
        case CotterAPIError.network:
            print("this is network error on registering user")
            break
        case CotterAPIError.status:
            print("this is not successful error")
            break
        default:
            print("error registering user: \(err)")
        }
    }
}

// call the API using our client
CotterAPIService.shared.registerUser(
    userID: "hello@example.com",
    cb: registerUserCb
)

2. Get a User

/* https://www.cotter.app/api/v0/user/:your_user_id */
CotterAPIService.shared.getUser(
  userID: <your-user-id>,
  cb: { response in
    // handle Result (Swift 5 enum) callback here
  }
)

Response:

{
  "ID": "9449e9e9-00e0-4d6b-a4b6-28c5b22b0b0f",
  "created_at": "2020-01-21T12:40:21.200727668Z",
  "update_at": "2020-01-21T12:40:21.200727668Z",
  "deleted_at": null,
  "issuer": "<your key ID>",
  "client_user_id": "<Your User Identifier (string)>",
  "enrolled": ["PIN", "BIOMETRIC"],
  "default_method": "BIOMETRIC"
}

Example:

func enrollCb(response: CotterResult<CotterUser>) {
    switch response {
    case .success(let resp):
        self.yourLabel.text = resp.enrolled.joined(separator: ", ")
    case .failure(let err):
        // we can handle multiple error results here
        switch err {
        case CotterAPIError.status(code: 500):
            print("internal server error")
        case CotterAPIError.status(code: 404):
            print("user not found")
        default:
            print(err.localizedDescription)
        }
    }
}

CotterAPIService.shared.getUser(userID:self.userID, cb:enrollCb)

Step 5. Enroll PIN or Biometric

For starting authentication flow, you need to have the following:

  • The UIViewController you want to attach Cotter to

  • The UIViewController MUST have a NavigationController set (i.e. self.navigationController cannot be nil)

// initialization
let cotter = Cotter(...)cotter.PinEnrollment.startEnrollment(
 vc: <your-vc>,
 animated: true,
 cb: <your-callback>
);

example:

class SomeUIVC: UIViewController {
  var cotter: Cotter?
  override func viewDidLoad() {
      super.viewDidLoad()
      // cotter initialization here
      self.cotter = Cotter(
          apiSecretKey: "588d6f67-0981-4718-899b-bcd512de1aca",
          apiKeyID: "w4FK6Zz0XIhtGY3o5biI",
          userID: "hello@example.com",
          cotterURL: "https://www.cotter.app/api/v0",
          configuration: [:]
        );
      cotter.startEnrollment(
        vc: self,
        animated: true,
        cb: { (token: String, err: Error?) in
            if err != nil {
                // handle error
                return
            }
            // handle success
        }
      )
  }
}

Step 6. Verify PIN and/or Biometrics on an action

The verification flow will automatically prompt for Biometric Verification if the user's device has an enrolled biometric. Otherwise, it will fallback to entering PIN. Starting the verification flow is exactly the same as starting the Enrollment Flow on step 5.

// initialization
let cotter = Cotter(...)

cotter.PinEnrollment.startTransaction(
  vc: <your-vc>,
  animated: true,
  cb: <your-callback>,
  hideClose: false, // hideClose param gives you the choice to show/hide the close button
  configuration: [:]
);

Example:

class SomeUIVC: UIViewController {
  var cotter: Cotter?

  override func viewDidLoad() {
      super.viewDidLoad()

      // cotter initialization here
      self.cotter = Cotter(
          apiSecretKey: "<your API_SECRET_KEY>",
          apiKeyID: "<your API_KEY_ID>",
          userID: "hello@example.com",
          cotterURL: "https://www.cotter.app/api/v0"
        );

      cotter.startTransaction(
        vc: self,
        animated: true,
        cb: { (token: String, err: Error?) in 
            if err != nil {
                // handle error
                return
            }
            // handle success
        },
        hideClose: false
      )
  }
}

🎉 You're done!

Additional Notes

The Callbacks

There are 2 types of callback:

1. HTTP Callbacks

HTTP Callbacks are the ones that you pass in to the start flow functions (startEnrollment, startTransaction, startUpdateProfile).

The callback form is as such:

// FinalCallbackAuth is the general callback function declaration
public typealias FinalAuthCallback = (_ token: String, _ error: Error?) -> Void

It takes in a token String and an optional Error object. Currently token String is not used in PIN or Biometric authentication. We're working on making the token useable.

Error types

For the FinalAuthCallback function, there are 3 types of CotterError that exist in the SDK. These include:

1. CotterError.biometricEnrollment

  • This error is produced when you fail to enroll your biometrics during the Enrollment flow in startEnrollment.

2. CotterError.biometricVerification

  • This error is produced when you fail to verify your biometrics during the Transaction flow in startTransaction.

3. CotterError.keychainError

  • This error is produced in all flows when the user's device is unable to attain its corresponding public/private keys.

However, you will almost always only encounter CotterError.biometricEnrollment and CotterError.biometricVerification errors in the resulting FinalAuthCallback function.

2. Authentication Callbacks

Authentication Callbacks are the ones that is passed in through the CotterAPIService. It uses the latest Result enum in Swift 5. The Authentication callback works similarly as the HTTP Callback, it can handle success and error cases as shown on the previous example.

The callback form is as such:

public typealias ResultCallback<Value> = (Result<Value, Error>) -> Void

What this definition says is that it takes a Result of a type Value, which Value can be any of the pre defined Cotter classes (such as CotterUser, CotterEvent, etc), and returns nothing.

Error types

When using the CotterAPIService class to call Cotter's API endpoints, there are 5 types of Cotter errors that you might encounter:

1. CotterAPIError.encoding

  • An 'encoding' error refers to an error encoding the HTTP Request.

2. CotterAPIError.decoding

  • A 'decoding' error refers to an error decoding the HTTP Response.

3. CotterAPIError.status(code: Int)

  • A 'status' error refers to the response having an invalid HTTP Status Code - e.g. Status 400 (Bad Request Error)

4. CotterAPIError.server(message: String)

  • A 'server' error means that our API server has responded to the request with an error message.

5. CotterAPIError.network

  • A 'network' error means that network conditions are poor, which can be due to bad internet connection.

Otherwise please open an issue at .

You need to set allowed methods for authentication your users. To allow PIN and BIOMETRIC, go to

📘
Installation
Set allowed Authentication Methods in the Developer Dashboard
Initialize Cotter as a dependency
Create a User
Enroll PIN or Biometric
Verify PIN and/or Biometrics on an action
our Github Issues page
https://dev.cotter.app/rules
Biometric and PIN using Cotter's SDK
Set both Biometric and PIN to be allowed