Git Product home page Git Product logo

ngx-oauth-client's Introduction

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

ngx-oauth-client's People

Contributors

0xmatt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

ngx-oauth-client's Issues

OAuth with basic authentication

Hello,
I am trying to get this working with OAuth and basic authentication.
So the client should be able to send a basic auth header in the token request, if I am correct this isn't implemented yet?
Can you confirm? If it's implemented, any example how to do this?

Override headers not working

Hello, I'm trying to add auth header to my request, but it seems it gets lost at this point (ngx-request.js):

NgxRequest.prototype.setHeaders = function (headers, override) {
        this.headers = new http_1.HttpHeaders(Object.assign(headers, override));
        return this;
};

headers param is correctly populated with
Object {Authorization: "Bearer 2f8e3907-93c5-4cd1-a81b-554d4811a675"},
and override param is undefined.
The problem is at the point when the script create the new http_1.HttpHeaders object.

The returned object has:

HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: }

Any hint? Thanks in advance!

Params are not able to be set on non get methods

As the title states, NgxRequest.setParams is only called if the request method is GET. All other methods need to be able to make use of this if a params key is set, however it will need to comply with the style that the HttpClient options uses, so it can't take object that we convert, but an instance of HttpParams itself. It's late, this is just a reminder to fix this tomorrow.

Multiple params for .get

Having an issue with passing an object into .get. Only the last property in the passed in object is being used. ie .get('posts', {limit: 10, offset: 10}) builds the url /posts?offset=10 and will disregard all other properties.

different hosts for auth and data

Hello, as discussed on a different issue (link), I would like to be able to have different hosts based on the functionality or data to access.
This means that the host param in the configuration api should be able to handle

  • an url for auth (ie, auth.server.com/oauth),
  • and another one (or more) for data after authentication (ie, data.server.com/v1).

As pointed out in the other issue the approach to extend and override should work in theory but as you said "this functionality will be removed", and I don't understand this statement.
I would like to know how much this is gonna last if I follow this path as you suggested.

I know this scenario could be not so common, but I'll give it a shot with your library before writing something from scratch.

As regards the implementation, as far as I can tell, the easiest way could be to add an optional parameter to the configuration api that stores 1 or more data hosts (all in the same network, sharing the auth token). What's behind the scene is a total mistery up to now, but I'll eventually dig into your code soon.

Thanks a lot in advance!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.