Skip to content

Latest commit

 

History

History
125 lines (100 loc) · 3.99 KB

Authentication.md

File metadata and controls

125 lines (100 loc) · 3.99 KB

Authentication

Manages user credentials between app sessions.

SDK Features that need Authentication

Feature Reason
Inbox Needs Authentication to view inbox messages that belong to a user.
Push Notifications Needs Authentication to sync push notification device tokens to the current user and Courier.
Preferences Needs Authentication to get and update notification preferences that belong to a user.

Getting Started

Put this code where you normally manage your user's state. The user's access to Inbox, Push Notifications and Preferences will automatically be managed by the SDK and stored in persistent storage. This means that if your user fully closes your app and starts it back up, they will still be "signed in".

1. Generate a JWT

To generate a JWT, you will need to:

  1. Create an endpoint on your backend
  2. Call this function inside that endpoint: Generate Auth Tokens
  3. Return the JWT

Here is a curl example with all the scopes needed that the SDK uses. Change the scopes to the scopes you need for your use case.

curl --request POST \
     --url https://api.courier.com/auth/issue-token \
     --header 'Accept: application/json' \
     --header 'Authorization: Bearer $YOUR_AUTH_KEY' \
     --header 'Content-Type: application/json' \
     --data
 '{
    "scope": "user_id:$YOUR_USER_ID write:user-tokens inbox:read:messages inbox:write:events read:preferences write:preferences read:brands",
    "expires_in": "$YOUR_NUMBER days"
  }'

2. Get a JWT in your app

Task {
    let userId = "your_user_id"
    let jwt = await YourBackend.generateCourierJWT(for: userId)
}

3. Sign your user in

Signed in users will stay signed in between app sessions.

Task {
    let userId = "your_user_id"
    await Courier.shared.signIn(accessToken: jwt, userId: userId)
}

If the token is expired, you can generate a new one from your endpoint and call Courier.shared.signIn(...) again. You will need to check the token manually for expiration or generate a new one when the user views a specific screen in your app. It is up to you to handle token expiration and refresh based on your security needs.

4. Sign your user out

This will remove any credentials that are stored between app sessions.

Task {
    await Courier.shared.signOut()
}

All Available Authentication Values

Task {
    let userId = await Courier.shared.userId
    let isUserSignedIn = await Courier.shared.isUserSignedIn
    
    let listener = await Courier.shared.addAuthenticationListener { userId in
        print(userId ?? "No userId found")
    }
    
    listener.remove()
}