auth http

hantsy edited this page Aug 10, 2017 · 2 revisions

Handle token based Authentication via IHttpInterceptor

Covalent provides a useful http intereceptor to interecept http request and response as AngularJS 1.x

This feature is included in the @covalent/http module, which we have installed in the former posts.

Create an IHttpInterceptor

When I wrote this post, I used a newer microservice sample as backend APIs which used Spring Session/Spring Security to handle session sharing and http authentication.

  1. When the client user is authenticated successfully, it will add a X-Auth-Token in the http response header.
  2. Store X-Auth-Token to local storage.
  3. Add this X-Auth-Token to any request header to access the protected resources.

Create an IHttpInterceptor implementation class to implement all requireds methods of this interface, and process token based authentication.

  1. onRequest, when starts a request, try to add X-Auth-Token into request headers.
  2. onResponse, when a request get a response successfully, try to check if there is a X-Auth-Token in the response header.
  3. onResponseError if got a 401 error in the response result, go to signin page.
const XAUTH_TOKEN_KEY = 'X-Auth-Token';

@Injectable()
export class AuthHttpInterceptor implements IHttpInterceptor {

  constructor(
    // @Inject(APP_CONFIG) config: AppConfig,
    private _jwt: JWT,
    private _router: Router
  ) { }

  onRequest(requestOptions: RequestOptionsArgs): RequestOptionsArgs {
    console.log('AuthHttpInterceptor::onRequest::' + requestOptions);

    const token = this._jwt.get();
    if (token) {
      console.log('restoring token from local storage...::' + token);
      requestOptions.headers.set(XAUTH_TOKEN_KEY, token);
    }
    return requestOptions;
  }

  onRequestError(requestOptions: RequestOptionsArgs): RequestOptionsArgs {
    console.log('AuthHttpInterceptor::onRequestError::' + requestOptions);
    return requestOptions;
  }

  onResponse(response: Response): Response {
    console.log('AuthHttpInterceptor::onResponse::' + response);
    const token = response.headers.get(XAUTH_TOKEN_KEY);

    if (token) {
      console.log('saving token to local storage...::' + token);
      this._jwt.save(token);
    }

    return response;
  }

  onResponseError(response: Response): Response {
    console.log('AuthHttpInterceptor::onResponseError::' + response);
    if (response.status === 401) {
      this._router.navigateByUrl('/auth/signin');
      return null;
    }
    return response;
  }
}

Register it in root module

Add the following to register it in AppModule.

// Covalent
CovalentHttpModule.forRoot({
  interceptors: [
	{
	  interceptor: AuthHttpInterceptor,
	  paths: ['**'],
	}
  ],
}),

Sample codes

The sample codes is hosted on my Github.com account.

https://github.com/hantsy/angular2-material-sample

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.