Skip to content
This repository has been archived by the owner on Oct 24, 2024. It is now read-only.

Handle errors during token renewal. Expose TokenManager [react, angular, vue] #551

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,74 @@
},
"disableOptimisticBPs": true
},
{
"type": "node",
"request": "launch",
"protocol": "auto",
"name": "okta-react Jest",
"cwd": "${workspaceFolder}/packages/okta-react",
"args": [
"node_modules/.bin/jest",
"--runInBand",
"--no-cache",
"${workspaceFolder}/${relativeFile}"
],
"sourceMaps": true,
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"env": {

},
"sourceMapPathOverrides": {
"webpack:///*": "/*",
},
"disableOptimisticBPs": true
},
{
"type": "node",
"request": "launch",
"protocol": "auto",
"name": "okta-angular Jest",
"cwd": "${workspaceFolder}/packages/okta-angular",
"args": [
"node_modules/.bin/jest",
"--runInBand",
"--no-cache",
"${workspaceFolder}/${relativeFile}"
],
"sourceMaps": true,
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"env": {

},
"sourceMapPathOverrides": {
"webpack:///*": "/*",
},
"disableOptimisticBPs": true
},
{
"type": "node",
"request": "launch",
"protocol": "auto",
"name": "okta-vue Jest",
"cwd": "${workspaceFolder}/packages/okta-vue",
"args": [
"node_modules/.bin/jest",
"--runInBand",
"--no-cache",
"${workspaceFolder}/${relativeFile}"
],
"sourceMaps": true,
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"env": {

},
"sourceMapPathOverrides": {
"webpack:///*": "/*",
},
"disableOptimisticBPs": true
},
]
}
15 changes: 15 additions & 0 deletions packages/okta-angular/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,10 @@ For PKCE flow, this should be left undefined or set to `['code']`.
- [`sessionStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage)
- [`cookie`](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie)

- `onTokenError` *(optional)* - callback function. Handles errors emitted by the internal TokenManager. The default handler will initiate a login flow. Passing a function here will override the default handler.

- `isAuthenticated` *(optional)* - callback function. By default, `OktaAuthService.isAuthenticated` will return true if both `getIdToken()` and `getAccessToken()` return a value. Setting a `isAuthenticated` function on the config will skip the default logic and call the supplied function instead. The function should return a Promise and resolve to either true or false.

### `OktaAuthModule`

The top-level Angular module which provides these components and services:
Expand Down Expand Up @@ -259,6 +263,12 @@ export class MyComponent {
}
```

#### `oktaAuth.login(fromUri?, additionalParams?)`

Calls `onAuthRequired` or redirects to Okta if `onAuthRequired` is undefined. This method accepts a `fromUri` parameter to push the user to after successful authentication, and an optional `additionalParams` object.

For more information on `additionalParams`, see the `oktaAuth.loginRedirect`](#oktaauthloginredirectfromuriadditionalparams) method below.

#### `oktaAuth.loginRedirect(fromUri?, additionalParams?)`

Performs a full page redirect to Okta based on the initial configuration. This method accepts a `fromUri` parameter to push the user to after successful authentication.
Expand Down Expand Up @@ -311,6 +321,11 @@ Returns the stored URI and query parameters stored when the `OktaAuthGuard` and/

## Contributing
We welcome contributions to all of our open-source packages. Please see the [contribution guide](https://github.com/okta/okta-oidc-js/blob/master/CONTRIBUTING.md) to understand how to structure a contribution.
#### `oktaAuth.getTokenManager()`

Returns the internal [TokenManager](https://github.com/okta/okta-auth-js#tokenmanager).

## Development

### Installing dependencies for contributions
We use [yarn](https://yarnpkg.com) for dependency management when developing this package:
Expand Down
17 changes: 0 additions & 17 deletions packages/okta-angular/src/okta/models/auth-required-function.ts

This file was deleted.

10 changes: 9 additions & 1 deletion packages/okta-angular/src/okta/models/okta.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,13 @@

import { InjectionToken } from '@angular/core';

import { AuthRequiredFunction } from './auth-required-function';
import { Router } from '@angular/router';

import { OktaAuthService } from '../services/okta.service';

export type AuthRequiredFunction = (oktaAuth: OktaAuthService, router: Router) => void;
export type IsAuthenticatedFunction = () => Promise<boolean>;
export type onSessionEndFunction = () => void;

export interface TestingObject {
disableHttpsCheck: boolean;
Expand All @@ -35,6 +41,8 @@ export interface OktaConfig {
onAuthRequired?: AuthRequiredFunction;
testing?: TestingObject;
tokenManager?: TokenManagerConfig;
isAuthenticated?: IsAuthenticatedFunction;
onSessionEnd?: onSessionEndFunction;
}

export const OKTA_CONFIG = new InjectionToken<OktaConfig>('okta.config.angular');
3 changes: 3 additions & 0 deletions packages/okta-angular/src/okta/models/token-manager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export interface TokenManager {
on: Function;
}
2 changes: 1 addition & 1 deletion packages/okta-angular/src/okta/okta.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import {
} from '@angular/router';

import { OktaAuthService } from './services/okta.service';
import { AuthRequiredFunction } from './models/auth-required-function';
import { AuthRequiredFunction } from './models/okta.config';

@Injectable()
export class OktaAuthGuard implements CanActivate {
Expand Down
24 changes: 22 additions & 2 deletions packages/okta-angular/src/okta/services/okta.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import {
buildConfigObject
} from '@okta/configuration-validation';

import { OKTA_CONFIG, OktaConfig } from '../models/okta.config';
import { OKTA_CONFIG, OktaConfig, AuthRequiredFunction } from '../models/okta.config';
import { UserClaims } from '../models/user-claims';

import packageInfo from '../packageInfo';
Expand All @@ -29,6 +29,7 @@ import packageInfo from '../packageInfo';
*/
import OktaAuth from '@okta/okta-auth-js';
import { Observable, Observer } from 'rxjs';
import { TokenManager } from '../models/token-manager';

@Injectable()
export class OktaAuthService {
Expand All @@ -46,6 +47,12 @@ export class OktaAuthService {
this.config = buildConfigObject(auth); // use normalized config object
this.config.scopes = this.config.scopes || [];

// Automatically enters login flow if token renew fails.
// The default behavior can be overriden by passing a function via config: `config.onAuthRequired`
if (!this.config.onSessionEnd) {
this.config.onSessionEnd = this._onSessionEnd.bind(this);
}

/**
* Scrub scopes to ensure 'openid' is included
*/
Expand All @@ -62,10 +69,23 @@ export class OktaAuthService {
this.$authenticationState = new Observable((observer: Observer<boolean>) => { this.observers.push(observer); });
}

_onSessionEnd() {
this.loginRedirect(this.router.url);
}

getTokenManager(): TokenManager {
return this.oktaAuth.tokenManager;
}

/**
* Checks if there is an access token and id token
*/
async isAuthenticated(): Promise<boolean> {
// Support a user-provided method to check authentication
if (this.config.isAuthenticated) {
return (this.config.isAuthenticated)();
}

const accessToken = await this.getAccessToken();
const idToken = await this.getIdToken();
return !!(accessToken || idToken);
Expand Down Expand Up @@ -147,7 +167,7 @@ export class OktaAuthService {
|| this.config.responseType
|| ['id_token', 'token'];

this.oktaAuth.token.getWithRedirect(params);
return this.oktaAuth.token.getWithRedirect(params); // can throw
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@ import { OktaAuthService } from '@okta/okta-angular';
selector: 'app-root',
template: `
<button id="home-button" routerLink="/"> Home </button>
<button id="login-button" *ngIf="!isAuthenticated" routerLink="/login"> Login </button>
<button id="login-button" *ngIf="!isAuthenticated" routerLink="/login" [queryParams]="{ fooParams: 'foo' }"> Login </button>
<button id="logout-button" *ngIf="isAuthenticated" (click)="logout()"> Logout </button>
<button id="protected-button" routerLink="/protected"> Protected </button>
<button id="protected-login-button" routerLink="/protected-with-data"> Protected Page w/ custom config </button>
<button id="protected-button" routerLink="/protected" [queryParams]="{ fooParams: 'foo' }"> Protected </button>
<button id="protected-login-button" routerLink="/protected-with-data"
[queryParams]="{ fooParams: 'foo' }"> Protected Page w/ custom config </button>

<router-outlet></router-outlet>
`,
Expand Down
128 changes: 128 additions & 0 deletions packages/okta-angular/test/spec/guard.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
jest.mock('@okta/okta-auth-js');

import { TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import OktaAuth from '@okta/okta-auth-js';

import {
OktaAuthModule,
OktaAuthService,
OktaAuthGuard,
} from '../../src';
import { ActivatedRouteSnapshot, RouterStateSnapshot, Router, RouterState } from '@angular/router';

const VALID_CONFIG = {
clientId: 'foo',
issuer: 'https://foo',
redirectUri: 'https://foo'
};

function createService(options) {
options = options || {};

const oktaAuth = options.oktaAuth || {};
oktaAuth.tokenManager = oktaAuth.tokenManager || { on: jest.fn() };
OktaAuth.mockImplementation(() => oktaAuth);

TestBed.configureTestingModule({
imports: [
RouterTestingModule.withRoutes([{ path: 'foo', redirectTo: '/foo' }]),
OktaAuthModule.initAuth(VALID_CONFIG)
],
providers: [OktaAuthService],
});
const service = TestBed.get(OktaAuthService);
service.getTokenManager = jest.fn().mockReturnValue({ on: jest.fn() });
service.isAuthenticated = jest.fn().mockReturnValue(Promise.resolve(options.isAuthenticated));
service.setFromUri = jest.fn();
service.loginRedirect = jest.fn();
return service;
}

describe('Angular auth guard', () => {

beforeEach(() => {
OktaAuth.mockClear();
});
afterEach(() => {
jest.restoreAllMocks();
});

describe('canActivate', () => {
describe('isAuthenticated() = true', () => {
it('returns true', async () => {
const service = createService({ isAuthenticated: true });
const guard = new OktaAuthGuard(service, null);
const res = await guard.canActivate(null, null);
expect(res).toBe(true);
});
});

describe('isAuthenticated() = false', () => {
let service: OktaAuthService;
let guard: OktaAuthGuard;
let state: RouterStateSnapshot;
let route: ActivatedRouteSnapshot;
let router;
beforeEach(() => {
service = createService({ isAuthenticated: false });
router = TestBed.get(Router);
guard = new OktaAuthGuard(service, router);
const routerState: RouterState = router.routerState;
state = routerState.snapshot;
route = state.root;
});

it('returns false', async () => {
const config = service.getOktaConfig();
const res = await guard.canActivate(route, state);
expect(res).toBe(false);
});

it('by default, calls "loginRedirect()"', async () => {
const config = service.getOktaConfig();
const res = await guard.canActivate(route, state);
expect(service.loginRedirect).toHaveBeenCalled();
});

it('calls "setFromUri" with baseUrl and query object', async () => {
const baseUrl = 'http://fake.url/path';
const query = '?query=foo&bar=baz';
const hash = '#hash=foo';
state.url = `${baseUrl}${query}${hash}`;
const queryObj = { 'bar': 'baz' };
route.queryParams = queryObj;
const res = await guard.canActivate(route, state);
expect(service.setFromUri).toHaveBeenCalledWith(baseUrl, queryObj);
});

it('onAuthRequired can be set on route', async () => {
const fn = route.data['onAuthRequired'] = jest.fn();
const res = await guard.canActivate(route, state);
expect(fn).toHaveBeenCalledWith(service, router);
});

it('onAuthRequired can be set on config', async () => {
const config = service.getOktaConfig();
const fn = config.onAuthRequired = jest.fn();

const res = await guard.canActivate(route, state);
expect(fn).toHaveBeenCalledWith(service, router);
});
});
});

it('Can create the guard via angular injection', () => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule.withRoutes([{ path: 'foo', redirectTo: '/foo' }]),
OktaAuthModule.initAuth(VALID_CONFIG)
],
providers: [OktaAuthService, OktaAuthGuard],
});
const guard = TestBed.get(OktaAuthGuard);
expect(guard.oktaAuth).toBeTruthy();
expect(guard.router).toBeTruthy();
expect(typeof guard.canActivate).toBe('function');
});
});
Loading