Implement Angular 2 Google login : NPM Package

angular2 google login

Using Google’s OAuth authentication has become one of the prime task while building any application. Using Google Sign-in method provides easy to use security mechanism, creates a trust in user, ease the development flow and provides a level of security to your application.

Google authentication technique is open for any language and one can integrate this using any commonly used language. I’ve created this package in Angular2. You can fork it on Github or download from NPM.

Here is a guide to use it. Obviously you are free to customize it, but make sure everything remains intact.

  • First of all open your CMD and run the following command in the working directory of your Angular2 app –

    npm install angular2-google-login

  • After completing the installation, import the package in the Angular2 component –

    import { AuthService, AppGlobals } from ‘angular2-google-login’;

  • Add the provider information in the component –

    providers: [AuthService];

  • Set the authentication parameter in constructor –

    constructor(private _googleAuth: AuthService){}

  • Set your unique and secret Google client Id. You can do this in ngOnInit() interface –

    AppGlobals.GOOGLE_CLIENT_ID = ‘SECRET_CLIENT_ID’;

  • Now use this code snippet to perform Google authentication –

    this._googleAuth.authenticateUser(()=>{ //YOUR_CODE_HERE });

  • After successful authentication, data is currently being saved in browser’s localstorage. You can do whatever your requirement says.
  • To logout the user and clear the session do this –

    this._googleAuth.userLogout(()=>{ //YOUR_CODE_HERE });

If you face any issue while using this package just visit GitHub and read the README.md file. Alternatively you can raise the issue and I’ll take a look into it.