auth http - hantsy/angular2-sample GitHub Wiki
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.
- When the client user is authenticated successfully, it will add a
X-Auth-Tokenin the http response header. - Store
X-Auth-Tokento local storage. - Add this
X-Auth-Tokento 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.
onRequest, when starts a request, try to addX-Auth-Tokeninto request headers.onResponse, when a request get a response successfully, try to check if there is aX-Auth-Tokenin the response header.onResponseErrorif 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.