Skip to content

0xMatt/ngx-oauth-client

Repository files navigation

npm version Build Status Coverage Status

ngx-oauth-client

ngx-oauth-client is an Angular4 HTTP/OAuth2 client utilizing the HttpClient. This package allows you to set up multiple clients to interface with many OAuth2 compliant APIs.

Check out the demo!

Bug-reports or feature request are welcome!

Getting started

Install it via npm:

npm install ngx-oauth-client -S

And add it as a dependency to your main module

import {NgxOAuthModule} from 'ngx-oauth-client';
@NgModule({
  imports: [
    NgxOAuthModule
  ],
})
export class AppModule {
}

Using the library is easy, just create your extending class and configure it:

import {NgxOAuthClient, DefaultHeaders, Configuration} from 'ngx-oauth-client';
@Configuration({
  host: 'https://jsonplaceholder.typicode.com'
})
@DefaultHeaders({
  'Content-Type': 'application/json',
  'Accept': 'application/json'
})
export class MyApiClient extends NgxOAuthClient {

}

Configuration

Configuration is done via the Configuration decorator, the api is simple

interface NgxOAuthConfig {
  host: string;
  token?: string;
  key?: string;
  secret?: string;
  storage_prefix? string;
}

OAuth2.0

Built-in support for authenticating via OAuth2 has been provided, you can use the getToken method to perform any authentication method to retrieve a token from the OAuth server.

You may use fetchToken(key?) to retrieve details about a specific token property or get the entire NgxOAuthResponse object by not supplying a value to the function parameter.

Client Credentials

MyApiClient.getToken().subscribe((token: NgxOAuthResponse) => {
  // Token is already set for you
  MyApiClient.fetchToken('access_token'); // your_token_from_response
});

Password

MyApiClient.getToken('password', {
  username: 'bob',
  password: '123123'
}).subscribe((token: NgxOAuthResponse) => {
  // Token is already set for you
  MyApiClient.fetchToken('access_token'); // your_access_token_from_response
  MyApiClient.fetchToken('refresh_token'); // your_refresh_token_from_response
});

Authorization Code

MyApiClient.getToken('authorization_code', {authorization_code: '123'}.subscribe((token: NgxOAuthResponse) => {
  // Token is already set for you
  MyApiClient.fetchToken('access_token'); // your_access_token_from_response
  MyApiClient.fetchToken('refresh_token'); // your_refresh_token_from_response
});

Interceptors

While the HttpClient now providers interceptors, they are in fact global. Having interceptor methods allows you to have client-specific interceptor rules.

Request Interceptor

The example demonstrates adding an authorization header to your requests if your criteria is met.

requestInterceptor(request) {
    const auth = this.fetchToken();
    if (auth) {
      return request.setHeaders({Authorization: auth.token_type + auth.access_token});
    }

    return request;
}

Response Interceptor

The response interceptor allows you to modify the return value from requests

responseInterceptor(request, response) {
  console.info(`Response from ${request.url}`, response);
  return response;
}

Error Interceptor

The error interceptor allows you to handle erroneous requests

errorInterceptor(request, error): Observable<any> {
  if (error.status === 401) {
    const refresh_token = this.fetchToken('refresh_token');
    if (!refresh_token) {
      return Observable.throw(error);
    }
    return this.getToken('refresh_token', {refresh_token}).switchMap(token => {
      return this.getClient().request(
        request.method,
        request.url,
        this.requestInterceptor(request.setHeaders({Authorization: `${token.token_type} ${token.access_token}`}))
      );
    });
  }
  return Observable.throw(error);
}

Credits