iOS Swift: Authorization

View on Github

iOS Swift: Authorization

Gravatar for
By Martin Walsh

This tutorial will show you how assign roles to your users, and use those claims to authorize or deny a user to perform certain actions in the app. We recommend that you log in to follow this quickstart with examples configured for your account.

I want to explore a sample app

2 minutes

Get a sample configured with your account settings or check it out on Github.

View on Github
System requirements: Cocoapods 1.9 | iOS 9+ | Xcode 11.4+

Many identity providers supply access claims which contain, for example, user roles or groups. You can request the access claims in your token with .scope("openid roles") or .scope("openid groups").

If an identity provider does not supply this information, you can create a Rule for assigning roles to users.

Create a Rule to Assign Roles

Create a rule that assigns the following access roles to your user:

  • An admin role
  • A regular user role

To assign roles, go to the New rule page. In the Access Control section, select the Set roles to a user template.

Edit the following lines from the default script to match the conditions that fit your needs:

const addRolesToUser = function (user) {
    const endsWith = '';

    if ( && ( - endsWith.length, === endsWith)) {
      return ['admin'];
    return ['user'];

The rule is checked every time a user attempts to authenticate.

  • If the user has a valid email and the domain is, the user gets the admin and user roles.
  • If the email contains anything else, the user gets the regular user role.

The claim is saved in the ID Token under the name

Depending on your needs, you can define roles other than admin and user. Read about the names you give your claims in the Rules documentation.

Test the Rule in Your Project

The claim with the roles you set is stored in the user's ID Token. It is a JSON Web Token (JWT) that holds claims. You can use a JWT decoding library to obtain the roles and perform access control. You can use the JWTDecode library.

import JWTDecode
guard let idToken = self.keychain.string(forKey: "id_token"),
    let jwt = try? decode(jwt: idToken),
    let roles = jwt.claim(name: "").array else {
    // Couldn't retrieve claim

if roles.contains("admin") {
    // Access Granted
    // Present Admin Screen
} else {
    // Access Denied
    // Show warning

Restrict Content Based on Access Level

Now you can recognize the users with different roles in your app. You can use this information to give and restrict access to selected features in your app to users with different roles.

In the sample project, the user with the admin role can access the admin panel.

Use Auth0 for FREE