Skip to content

Authentication & Authorization in Gauzy

Rahul R edited this page Nov 23, 2023 · 23 revisions

Authentication vs Authorization

From this answer on StackOverflow:

Authentication is the process of ascertaining that somebody really is who they claim to be.

Authorization refers to rules that determine who is allowed to do what. E.g. Adam may be authorized to create and delete databases, while Usama is only authorized to read.

Authentication in Gauzy

Authentication in Gauzy is done by issuing JWT tokens.

Authentication in the front-end

  1. For restricting certain modules which only need to be available to logged-in users, we can use the AuthGuard i.e. ./@core/auth/auth.guard
  2. All modules which fall under the /pages route already have the AuthGuard. This is done in app-routing.module.ts
{
 path: 'pages',
 loadChildren: () =>
 import('./pages/pages.module').then((m) => m.PagesModule),
 canActivate: [AuthGuard, AppModuleGuard]
}

Authentication in the back-end

  1. In the backend, authentication is achieved through Nestjs Passport Strategy.
  2. Any controller or route can be made "private" so that only logged-in users have access to it using AuthGuard from @nestjs/passport. This can be used before any controller or route. If used on a controller, all routes will become private.

Using AuthGuard for a controller:

@UseGuards(AuthGuard('jwt'))
@Controller()
export class CandidateController extends CrudController<Candidate>

Using AuthGuard for a single route:

@UseGuards(AuthGuard('jwt'))
@Post('/emails')
async createManyWithEmailsId(

Authorization in Gauzy

  1. Gauzy uses a basic custom implementation of Role-based access control (RBAC) for Authorization.
  2. In short, every user has a 'role' and each role has 'permissions'.
  3. For any UI page, component, or backend API we can check permissions and conditionally enable/disable the pages/end-points.

Authorization in the front-end

  1. When a user logs in, the permissions are loaded & kept in the store. So to access the available permissions for a user we do not need to make an API call again. If the permissions change, the change is reflected in the next hard refresh of the page.
  2. There is a utility function hasPermission which can be used directly to check for permission.

The utility function can be used like:

this.store.hasPermission(PermissionsEnum.PUBLIC_PAGE_EDIT);

It is recommended to subscribe to userRolePermissions in the store and use it like this:

this.store.userRolePermissions$
 .pipe(takeUntil(this._ngDestroy$))
 .subscribe(() => {
   this.hasPermissionE = this.store.hasPermission(PermissionsEnum.ORG_EXPENSES_VIEW);
  });

Authorization in the back-end

  1. We can easily restrict APIs to only respond to users who have a certain permission using the PermissionGuard i.e. api/src/app/shared/guards/auth/permission.guard.ts
  2. If any controller or route has the PermissionGuard, the API will only be available when a user with that specific permission is logged in.
  3. It can be used like:
@UseGuards(PermissionGuard)
@Permissions(PermissionsEnum.ORG_CANDIDATES_INTERVIEWERS_EDIT)
@Delete('deleteBulkByInterviewId')
async deleteBulkByInterviewId( ...

Important note about using roles directly for Authorization!

Though there are RoleGuards available in both front-end & back-end it is highly recommended NOT to use them unless totally required. Also, any condition like role === RolesEnum.ADMIN etc. should be thought through, double-checked and avoided at all costs, unless absolutely necessary, any such condition should go through a stringent review.


Steps to configure "Google Application"

Create the Google Application

  1. To use google OAuth, we have to create application on your google console.
  2. Go to console devloper and create an application from screen.
  3. Click on "NEW PROJECT" and fill required details and then click the "Create" button.

Setup "OAuth consent screen"

  1. Click “OAuth consent screen” menu at the sidebar from screen.
  2. Select "External" option so the application can be used by any google account and then click CREATE.
  3. On the consent screen, make sure you only fill the "App Name" and "User support email" and "Developer contact information" nothing else because this is just for testing purposes. Click "SAVE AND CONTINUE" button from screen.

Get App credentials

To get app credentials click on “Credentials” menu at the sidebar.

  1. Click "CREATE CREDENTIALS" button on top header and select "OAuth Client ID" from screen.
  2. Select "Web applications" option from next "Create OAuth client ID" screen then fill the "Authorized JavaScript origins" and "Authorized redirect URIs" URI.
  3. The "Authorized JavaScript origins" refers to where our request will be coming.
i.e. Authorized redirect URIs - http://localhost:3000
  1. The "Authorized redirect URIs" refers to the particular endpoint in our app where google will return the response after authenticate a user.
i.e. Authorized redirect URIs - http://localhost:3000/api/auth/google/callback
  1. Click "CREATE" button. You should get your app credentials from the screen.
  2. Copy the credentials and save into the .env file like below or you can check into the .env.sample file.
GOOGLE_CLIENT_ID=XXXXXXX
GOOGLE_CLIENT_SECRET=XXXXXXX
GOOGLE_CALLBACK_URL=http://localhost:3000/api/auth/google/callback

Steps to configure "Facebook Application"

Create the Facebook Application

  1. Login to your Facebook account and navigate to https://developers.facebook.com

  2. If you not registered for Facebook developer account, then you need to register Facebook developer from https://developers.facebook.com.

  3. If you were already registered for Facebook developer account, then Click on "My Apps" >> "Create App".

Setup Create App Screen

  1. Make sure you fill all the required details from screen.

  2. From the "PRODUCTS" list page click on “Set Up” button from product with name “Facebook Login”.

  3. In the left side menu, click on the “Facebook Login” link to expand the sub menu. Click on “Settings” from the sub menu.

  4. Please enter "Valid OAuth Redirect URIs" and "Redirect URI to Check".

  5. How to get to more settings:

a) Click "Use cases" in the sidebar menu and next click button "Customize" next to "Authentication and account creation"

image

b) On the next page click the "Go to Settings" button

image

so you will see a page like below:

image

i.e. Valid OAuth Redirect URIs - http://localhost:3000
i.e. Redirect URI to Check - http://localhost:3000/api/auth/facebook/callback

Get App credentials

  1. Now expand the "App settings" menu and select Basic. Here you can find the App ID and App Secret.

  2. There is also a "Client token" in the "Security" block in the "App settings" -> "Advanced" menu

  3. Copy the credentials and save into the .env file like below or you can check into the .env.sample file.

FACEBOOK_CLIENT_ID=XXXXXXX
FACEBOOK_CLIENT_SECRET=XXXXXXX
FACEBOOK_CALLBACK_URL=http://localhost:3000/api/auth/facebook/callback

Steps to configure "GitHub Application"

Note: You can create and register an OAuth app under your personal account or under any organization you have administrative access to. A user or organization can own up to 100 OAuth apps.

  1. In the upper-right corner of any page, click your profile photo, then click Settings.

image

  1. In the left sidebar, click Developer settings.

image

  1. In the left sidebar, click OAuth apps.

image

  1. Click New OAuth App.

Note: If you haven't created an app before, this button will say, Register a new application.

  1. Register a New OAuth Application.

image

Warning: Only use information in your OAuth app that you consider public. Avoid using sensitive data, such as internal URLs, when creating an OAuth app.

  1. In "Authorization callback URL", type the callback URL of your app.

image

Note: OAuth apps cannot have multiple callback URLs, unlike GitHub Apps.

  1. Get App Credentials (Copy the "Client ID" and "Client Secret" from the registered OAuth application).
  2. Save the credentials in the .env file.
GAUZY_GITHUB_OAUTH_CLIENT_ID=XXXXXXX
GAUZY_GITHUB_OAUTH_CLIENT_SECRET=XXXXXXX
GAUZY_GITHUB_OAUTH_CALLBACK_URL=http://localhost:3000/api/auth/github/callback

Steps to configure Twiiter Application

Step 1: Create a Twitter Developer Account

  1. Go to the Twitter Developer platform at https://developer.twitter.com/.
  2. Sign in with your Twitter account or create a new account if you don't have one.

image

Step 2: Create a Twitter App

  1. Navigate to the Twitter Developer Console.
  2. Click on the "Projects & Apps" tab.

image

  1. Click the "Create App" button.

image

  1. Fill in the required information (name, description, developer agreement) and click "Create."

Step 3: Generate API Keys and Access Tokens.

  1. In your app, go to the "Keys and Tokens" tab.

image

  1. Copy the API key and secret under the "Consumer API keys" section.

image

Step 4: Configure App Settings

  1. Go to the "Settings" tab for your app.

image

  1. Under "App permissions," choose the appropriate level of access.

image

  1. Save your changes.

Step 5: Enable 3-legged OAuth

  1. In the "Settings" tab, go to the "Authentication settings" section.
  2. Enable the "3-legged OAuth" option.

Step 6: Callback URL

  1. Under "App details," specify your callback URL (e.g., http://localhost:3000/api/auth/twitter/callback).

image

Step 7: Update .env File

  1. Create a .env file in the root of your project.
  2. Add the following lines to the .env file:
# Twitter OAuth Configuration
TWITTER_CLIENT_ID=YOUR_API_KEY
TWITTER_CLIENT_SECRET=YOUR_API_SECRET_KEY
TWITTER_CALLBACK_URL=http://localhost:3000/api/auth/twitter/callback

Steps to configure LinkedIn OAuth Application

Step 1: Create a LinkedIn Developer Account

  1. Go to the LinkedIn Developer platform at https://www.linkedin.com/developers/.
  2. Sign in with your LinkedIn account or create a new account if you don't have one.

Step 2: Create a New App

  1. Once logged in, click on the "My Apps" tab.

image

  1. Click the "Create App" button.

image

  1. Fill in the required information for your app (app name, description, and company).
  2. Accept the LinkedIn Developer Program Agreement and click "Create App."

image

Step 3: Obtain OAuth Credentials

  1. In the app dashboard, go to the "Auth" section.
  2. Under "Authentication Keys," note the Client ID and Client Secret. These are your OAuth credentials.

image

Step 4: Add Redirect URLs

  1. Under the "Auth" section, find the "Redirect URLs" field.
  2. Add the callback URL where LinkedIn will redirect users after they grant access. Example: http://localhost:3000/api/auth/linkedin/callback.

image

Step 5: Set Permissions

  1. Under the "Auth" section, find the "OAuth 2.0 scopes" field.
  2. Choose the necessary permissions your app requires, such as "r_liteprofile" for basic profile information.

Step 6: Save Changes

  1. Scroll to the bottom of the page and click the "Update" button to save your changes.

Step 7: Create/Edit a .env File

  1. In the root directory of your project, create a file named .env.
  2. Add the following lines to the .env file:
# LinkedIn OAuth Configuration
LINKEDIN_CLIENT_ID=YOUR_CLIENT_ID
LINKEDIN_CLIENT_SECRET=YOUR_CLIENT_SECRET
LINKEDIN_CALLBACK_URL=http://localhost:3000/api/auth/linkedin/callback

Steps to configure Microsoft Application

Step 1: Register a Microsoft Application (Create a Microsoft Online app for social login)

  1. Go to the Azure portal at (https://portal.azure.com).
  2. Sign in with your Microsoft account or create a new account if needed.
  3. From the portal home page, click the navigation menu, click All Services:
  4. On the All services page, in the navigation pane, click Identity, and then, in the primary pane, click App registrations:

microsoft-menu

Step 2: Create a New App Registration

  1. In the Azure portal, navigate to "Azure Active Directory" > "App registrations."

microsoft-app-registrations

  1. On the App registrations page, click New Registration:

microsoft-new-registration

  1. Fill in the required information, including the application name and supported account types.

microsoft-app-name

  1. In the Supported account types section, select Accounts in any organizational directory (Any Azure AD directory – Multi-Tenant and personal Microsoft accounts (e.g., Skype, Xbox):

microsoft-account-type

  1. Set the redirect URI(s) where Microsoft will redirect users after they grant access. Typically, it's in the format http://localhost:3000/api/auth/microsoft/callback.

microsoft-add-redirect

Step 3: Obtain Application (Client) ID and Client Secret

  1. After your application has been created, copy the Application (client) ID: You'll need both the client ID and the client secret in order to configure Microsoft Online as a social login provider.

image

  1. In the app registration, go to "Certificates & secrets."

microsoft-manage-menu

  1. Under "Client secrets," click on "New client secret."

microsoft-new-client-secret

  1. Provide a description, choose an expiration, and click "Add."

microsoft-add-secret-dialog

  1. Note the generated client secret value immediately as it will not be visible again.

Step 4: Configure Authentication

  1. In the app registration, go to "Authentication."
  2. Configure the platform (Web or Mobile) and set the redirect URIs.
  3. Save your changes.

Step 5: Set API Permissions

  1. In the app registration, go to "API permissions."

image

  1. Click on "Add a permission" and choose the appropriate APIs (e.g., Microsoft Graph).

image

  1. Configure delegated or application permissions as needed.
  2. Grant admin consent if required.

Step 6: Create/Edit a .env File

  1. In the root directory of your project, create a file named .env.
  2. Add the following lines to the .env file:
# Microsoft OAuth Configuration
MICROSOFT_GRAPH_API_URL=https://graph.microsoft.com/v1.0/me
MICROSOFT_AUTHORIZATION_URL=https://login.microsoftonline.com/common/oauth2/v2.0/authorize
MICROSOFT_TOKEN_URL=https://login.microsoftonline.com/common/oauth2/v2.0/token
MICROSOFT_CLIENT_ID=YOUR_CLIENT_ID
MICROSOFT_CLIENT_SECRET=YOUR_CLIENT_SECRET
MICROSOFT_CALLBACK_URL=http://localhost:3000/api/auth/microsoft/callback
Clone this wiki locally