Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/descope/angular-sdk

Angular library used to integrate with Descope
https://github.com/descope/angular-sdk

angular angular-sdk angularjs authentication descope jwt sdk

Last synced: about 1 month ago
JSON representation

Angular library used to integrate with Descope

Awesome Lists containing this project

README

        

# IMPORTANT NOTE: This repository is _DEPRECATED_.

Descope Angular SDK has been moved to the [descope-js](https://github.com/descope/descope-js/tree/main/packages/sdks/angular-sdk) repoistory.

---

# Descope SDK for Angular

The Descope SDK for Angular provides convenient access to the Descope for an application written on top of Angular. You can read more on the [Descope Website](https://descope.com).

## Requirements

- The SDK supports Angular version 16 and above.
- A Descope `Project ID` is required for using the SDK. Find it on the [project page in the Descope Console](https://app.descope.com/settings/project).

## Installing the SDK

Install the package with:

```bash
npm i --save @descope/angular-sdk
```

Add Descope type definitions to your `tsconfig.ts`

```
"compilerOptions": {
"typeRoots": ["./node_modules/@descope"],

}
```

## Usage

### NgModule - Import `DescopeAuthModule` to your application

`app.module.ts`

```ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { DescopeAuthModule } from '@descope/angular-sdk';

@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
DescopeAuthModule.forRoot({
projectId: ''
})
],
bootstrap: [AppComponent]
})
export class AppModule {}
```

### Standalone Mode - Configure Descope SDK for your application

`main.ts`

```ts
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { DescopeAuthConfig } from '@descope/angular-sdk';

bootstrapApplication(AppComponent, {
providers: [
{ provide: DescopeAuthConfig, useValue: { projectId: '' } }
]
}).catch((err) => console.error(err));
```

### Use Descope to render specific flow

You can use **default flows** or **provide flow id** directly to the descope component

#### 1. Default flows

`app.component.html`

```angular2html


Loading...

```

`app.component.ts`

```ts
import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
// Optionally, you can show/hide loading indication until the flow page is ready
// See usage in onReady() method and the html template
isLoading = true;

onSuccess(e: CustomEvent) {
console.log('SUCCESSFULLY LOGGED IN', e.detail);
}

onError(e: CustomEvent) {
console.log('ERROR FROM LOG IN FLOW', e.detail);
}

onReady() {
this.isLoading = false;
}
}
```

#### 2. Provide flow id

```angular2html
"
(error)=""

>
```

#### Standalone Mode

All components in the sdk are standalone, so you can use them by directly importing them to your components.

### Use the `DescopeAuthService` and its exposed fields (`descopeSdk`, `session$`, `user$`) to access authentication state, user details and utilities

This can be helpful to implement application-specific logic. Examples:

- Render different components if current session is authenticated
- Render user's content
- Logout button

`app.component.html`

```angular2html

You are not logged in


LOGOUT

User: {{userName}}


```

`app.component.ts`

```ts
import { Component, OnInit } from '@angular/core';
import { DescopeAuthService } from '@descope/angular-sdk';

@Component({
selector: 'app-home',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
isAuthenticated: boolean = false;
userName: string = '';

constructor(private authService: DescopeAuthService) {}

ngOnInit() {
this.authService.session$.subscribe((session) => {
this.isAuthenticated = session.isAuthenticated;
});
this.authService.user$.subscribe((descopeUser) => {
if (descopeUser.user) {
this.userName = descopeUser.user.name ?? '';
}
});
}

logout() {
this.authService.descopeSdk.logout();
}
}
```

### Session Refresh

`DescopeAuthService` provides `refreshSession` and `refreshUser` methods that triggers a single request to the Descope backend to attempt to refresh the session or user. You can use them whenever you want to refresh the session/user. For example you can use `APP_INITIALIZER` provider to attempt to refresh session and user on each page refresh:

`app.module.ts`

```ts
import { APP_INITIALIZER, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { DescopeAuthModule, DescopeAuthService } from '@descope/angular-sdk';
import { zip } from 'rxjs';

export function initializeApp(authService: DescopeAuthService) {
return () => zip([authService.refreshSession(), authService.refreshUser()]);
}

@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
DescopeAuthModule.forRoot({
projectId: ''
})
],
providers: [
{
provide: APP_INITIALIZER,
useFactory: initializeApp,
deps: [DescopeAuthService],
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule {}
```

#### Standalone Mode Note:

You can use the same approach with `APP_INITIALIZER` in standalone mode, by adding it to `providers` array of the application.

### Descope Interceptor

You can also use `DescopeInterceptor` to attempt to refresh session on each HTTP request that gets `401` or `403` response:

`app.module.ts`

```ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import {
HttpClientModule,
provideHttpClient,
withInterceptors
} from '@angular/common/http';
import { DescopeAuthModule, descopeInterceptor } from '@descope/angular-sdk';

@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
HttpClientModule,
DescopeAuthModule.forRoot({
projectId: '',
pathsToIntercept: ['/protectedPath']
})
],
providers: [provideHttpClient(withInterceptors([descopeInterceptor]))],
bootstrap: [AppComponent]
})
export class AppModule {}
```

`DescopeInterceptor`:

- is configured for requests that urls contain one of `pathsToIntercept`. If not provided it will be used for all requests.
- attaches session token as `Authorization` header in `Bearer ` format
- if requests get response with `401` or `403` it automatically attempts to refresh session
- if refresh attempt is successful, it automatically retries original request, otherwise it fails with original error

**For more SDK usage examples refer to [docs](https://docs.descope.com/build/guides/client_sdks/)**

### Session token server validation (pass session token to server API)

When developing a full-stack application, it is common to have private server API which requires a valid session token:

![session-token-validation-diagram](https://docs.descope.com/static/SessionValidation-cf7b2d5d26594f96421d894273a713d8.png)

Note: Descope also provides server-side SDKs in various languages (NodeJS, Go, Python, etc). Descope's server SDKs have out-of-the-box session validation API that supports the options described bellow. To read more about session validation, Read [this section](https://docs.descope.com/build/guides/gettingstarted/#session-validation) in Descope documentation.

You can securely communicate with your backend either by using `DescopeInterceptor` or manually adding token to your requests (ie. by using `DescopeAuthService.getSessionToken()` helper function)

### Helper Functions

You can also use the following helper methods on `DescopeAuthService` to assist with various actions managing your JWT.

- `getSessionToken()` - Get current session token.
- `getRefreshToken()` - Get current refresh token.
- `isAuthenticated()` - Returns boolean whether user is authenticated
- `refreshSession` - Force a refresh on current session token using an existing valid refresh token.
- `refreshUser` - Force a refresh on current user using an existing valid refresh token.
- `isSessionTokenExpired(token = getSessionToken())` - Check whether the current session token is expired. Provide a session token if is not persisted.
- `isRefreshTokenExpired(token = getRefreshToken())` - Check whether the current refresh token is expired. Provide a refresh token if is not persisted.
- `getJwtRoles(token = getSessionToken(), tenant = '')` - Get current roles from an existing session token. Provide tenant id for specific tenant roles.
- `getJwtPermissions(token = getSessionToken(), tenant = '')` - Fet current permissions from an existing session token. Provide tenant id for specific tenant permissions.

### Refresh token lifecycle

Descope SDK is automatically refreshes the session token when it is about to expire. This is done in the background using the refresh token, without any additional configuration.

If the Descope project settings are configured to manage tokens in cookies.
you must also configure a custom domain, and set it as the `baseUrl` in `DescopeAuthModule`.

### Descope Guard

`angular-sdk` provides a convenient route guard that prevents from accessing given route for users that are not authenticated:

```ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ProtectedComponent } from './protected/protected.component';
import { descopeAuthGuard } from '@descope/angular-sdk';
import { LoginComponent } from './login/login.component';

const routes: Routes = [
{
path: 'step-up',
component: ProtectedComponent,
canActivate: [descopeAuthGuard],
data: { descopeFallbackUrl: '/' }
},
{ path: 'login', component: LoginComponent },
{ path: '**', component: HomeComponent }
];

@NgModule({
imports: [RouterModule.forRoot(routes, { enableTracing: false })],
exports: [RouterModule]
})
export class AppRoutingModule {}
```

If not authenticated user tries to access protected route they will be redirected to `descopeFallbackUrl`

### Token Persistence

Descope stores two tokens: the session token and the refresh token.

- The refresh token is either stored in local storage or an `httpOnly` cookie. This is configurable in the Descope console.
- The session token is stored in either local storage or a JS cookie. This behavior is configurable via the `sessionTokenViaCookie` prop in the `DescopeAuthModule` module.

However, for security reasons, you may choose not to store tokens in the browser. In this case, you can pass `persistTokens: false` to the `DescopeAuthModule` module. This prevents the SDK from storing the tokens in the browser.

Notes:

- You must configure the refresh token to be stored in an `httpOnly` cookie in the Descope console. Otherwise, the refresh token will not be stored, and when the page is refreshed, the user will be logged out.
- You can still retrieve the session token using the `session` observable of `DescopeAuthService`.

### Last User Persistence

Descope stores the last user information in local storage. If you wish to disable this feature, you can pass `storeLastAuthenticatedUser: false` to the `DescopeAuthModule` module. Please note that some features related to the last authenticated user may not function as expected if this behavior is disabled.

### Widgets

Widgets are components that allow you to expose management features for tenant-based implementation. In certain scenarios, your customers may require the capability to perform managerial actions independently, alleviating the necessity to contact you. Widgets serve as a feature enabling you to delegate these capabilities to your customers in a modular manner.

Important Note:

- For the user to be able to use the widget, they need to be assigned the `Tenant Admin` Role.

#### User Management

The `UserManagement` widget will let you embed a user table in your site to view and take action.

The widget lets you:

- Create a new user
- Edit an existing user
- Activate / disable an existing user
- Reset an existing user's password
- Remove an existing user's passkey
- Delete an existing user

Note:

- Custom fields also appear in the table.

###### Usage

```html

```

Example:
[Manage Users](./projects/demo-app/src/app/manage-users/manage-users.component.html)

#### Role Management

The `RoleManagement` widget will let you embed a role table in your site to view and take action.

The widget lets you:

- Create a new role
- Change an existing role's fields
- Delete an existing role

Note:

- The `Editable` field is determined by the user's access to the role - meaning that project-level roles are not editable by tenant level users.
- You need to pre-define the permissions that the user can use, which are not editable in the widget.

###### Usage

```html

```

Example:
[Manage Roles](./projects/demo-app/src/app/manage-roles/manage-roles.component.html)

#### AccessKeyManagement

The `AccessKeyManagement` widget will let you embed an access key table in your site to view and take action.

The widget lets you:

- Create a new access key
- Activate / deactivate an existing access key
- Delete an exising access key

###### Usage

```html

```

Example:
[Manage Access Keys](./projects/demo-app/src/app/manage-access-keys/manage-access-keys.component.html)

#### AuditManagement

The `AuditManagement` widget will let you embed an audit table in your site.

###### Usage

```html

```

Example:
[Manage Audit](./projects/demo-app/src/app/manage-audit/manage-audit.component.html)

#### UserProfile

The `UserProfile` widget lets you embed a user profile component in your app and let the logged in user update his profile.

The widget lets you:

- Update user profile picture
- Update user personal information
- Update authentication methods
- Logout

###### Usage

```angular2html
"
/>
```

Example:
[My User Profile](./projects/demo-app/src/app/my-user-profile/my-user-profile.component.html)

## Code Example

You can find an example angular app in the [examples folder](./projects/demo-app).

### Setup

To run the examples, create `environment.development.ts` file in `environments` folder.

```ts
import { Env } from './conifg';

export const environment: Env = {
descopeProjectId: ''
};
```

Find your Project ID in the [Descope console](https://app.descope.com/settings/project).

### Run Example

Run the following command in the root of the project to build and run the example:

```bash
npm i && npm start
```

### Example Optional Env Variables

See the following table for customization environment variables for the example app:

| Env Variable | Description | Default value |
| -------------------- | ------------------------------------------------------------------------------------------------------------- | ----------------- |
| descopeFlowId | Which flow ID to use in the login page | **sign-up-or-in** |
| descopeBaseUrl | Custom Descope base URL | None |
| descopeBaseStaticUrl | Custom Descope base static URL | None |
| descopeTheme | Flow theme | None |
| descopeLocale | Flow locale | Browser's locale |
| descopeRedirectUrl | Flow redirect URL for OAuth/SSO/Magic Link/Enchanted Link | None |
| descopeTenantId | Flow tenant ID for SSO/SAML | None |
| descopeDebugMode | **"true"** - Enable debugger**"false"** - Disable flow debugger | None |
| descopeStepUpFlowId | Step up flow ID to show to logged in user (via button). e.g. "step-up". Button will be hidden if not provided | None |
| descopeTelemetryKey | **String** - Telemetry public key provided by Descope Inc | None |
| descopeBackendUrl | Url to your test backend app in case you want to test e2e | None |

Example `environment.development.ts` file:

```ts
import { Env } from './conifg';

export const environment: Env = {
descopeProjectId: '',
descopeBaseUrl: '',
descopeBaseStaticUrl: '',
descopeFlowId: 'sign-in',
descopeDebugMode: false,
descopeTheme: 'os',
descopeLocale: 'en_US',
descopeRedirectUrl: '',
descopeTelemetryKey: '',
descopeStepUpFlowId: 'step-up',
descopeBackendUrl: 'http://localhost:8080/protected'
};
```

## Troubleshooting

If you encounter warning during build of your application:

```
▲ [WARNING] Module 'lodash.get' used by 'node_modules/@descope/web-component/node_modules/@descope/core-js-sdk/dist/index.esm.js' is not ESM
```

add `lodash.get` to allowed CommonJS dependencies in `angular.json`

```json
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"allowedCommonJsDependencies": ["lodash.get"],

}

}

}
```

## FAQ

### I updated the user in my backend, but the user / session token are not updated in the frontend

The Descope SDK caches the user and session token in the frontend. If you update the user in your backend (using Descope Management SDK/API for example), you can call `me` / `refresh` from `descopeSdk` member of `DescopeAuthService` to refresh the user and session token. Example:

```ts
import { DescopeAuthService } from '@descope/angular-sdk';

export class MyComponent {
// ...
constructor(private authService: DescopeAuthService) {}

handleUpdateUser() {
myBackendUpdateUser().then(() => {
this.authService.descopeSdk.me();
// or
this.authService.descopeSdk.refresh();
});
}
}
```

## Learn More

To learn more please see the [Descope Documentation and API reference page](https://docs.descope.com/).

## Contact Us

If you need help you can email [Descope Support](mailto:[email protected])

## License

The Descope SDK for Angular is licensed for use under the terms and conditions of the [MIT license Agreement](./LICENSE).