Authentication demo with Angular and .NET

OAuth2 with Angular 9 We are going to build an Angular App uisng the angulatx-social-login package and will be using Google as my authentication provider. Steps: Create a google App and get clientID: As we

OAuth2 with Angular 9

We are going to build an Angular App uisng the angulatx-social-login package and will be using Google as my authentication provider.

Steps:

Create a google App and get clientID:

As we discussed in the previous article we would need to send an authentication request, to the Authentication server for getting the ID token and user’s credentials. So we would need a way for letter the google Authentication server know who we are for it we would need Client ID which is generated by the Google APP Console

Create new Project >set up OAuth consent >go to credentials/OAuth ClientID/WebApplication and enter your URL(in my case http:localhost:4600) in both Authorized havascript origin and Authorized redirect URL’s. It will generate a ClientID and secret Key which you need to save them.

Create an Angular Project

First lets run the command for creating angular app with routing “No”

ng new <appname>

Setting up Authentication

Now let’s add the Authentication Library to the app. In this tutorial, we are going to use angularx-social-login┬ápackage.

npm install --save angularx-socoalx-login

With this we have the required library to simplify handling the auth process.

Now let update the AppModule to include these classes also note in the providers where we have clientID you would need to replace with actual clientID.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

import {SocialLoginModule, SocialAuthServiceConfig } from "angularx-social-login";
import { GoogleLoginProvider } from "angularx-social-login";


@NgModule({
  declarations: [
    AppComponent  ],
  imports: [
    BrowserModule,
    SocialLoginModule // Place SocialLoginModule in imports
  ],
  providers: [
    {
      provide: 'SocialAuthServiceConfig',
      useValue: {
        autoLogin: false,
        providers: [
          {
            id: GoogleLoginProvider.PROVIDER_ID,
            provider: new GoogleLoginProvider(
              'ClientID'
            ),
          },
        ],
      } as SocialAuthServiceConfig,
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now with the above code we have set up google authentication.

Adding Sign-in and Sign-out feature

Create a new demo component and update it as below

import { Component, OnInit } from '@angular/core';

import { SocialAuthService, SocialUser } from "angularx-social-login";
import { GoogleLoginProvider } from "angularx-social-login";
 

@Component({
  selector: 'app-demo',
  templateUrl: './demo.component.html',
  styleUrls: ['./demo.component.css']
})
export class DemoComponent implements OnInit {

  constructor(private authService: SocialAuthService) { }

  signInWithGoogle():void {
    this.authService.signIn(GoogleLoginProvider.PROVIDER_ID);
  }

  signOut(): void {
    this.authService.signOut();
  }
}

<button type="button" (click)="signInWithGoogle()">Google</button>

so we have done the following in the above code:

we have imported the necessary libraries and then created 2 methods one for login and the other for logout. When a user clicks on the login button the Authorisation request will be sent to Google and we will end up the Auth screen

Consuming the User Information

Once the user is authenticated the server will return an ID token which we will consume now. So for it lets create a SocialUser Object which will hold the information. so let’s update the code as below.

import { Component, OnInit } from '@angular/core';

import { SocialAuthService, SocialUser } from "angularx-social-login";
import { GoogleLoginProvider } from "angularx-social-login";
 

@Component({
  selector: 'app-demo',
  templateUrl: './demo.component.html',
  styleUrls: ['./demo.component.css']
})
export class DemoComponent implements OnInit {

  user: SocialUser;
  loggedIn: boolean;

  constructor(private authService: SocialAuthService) { }

  signInWithGoogle():void {
    this.authService.signIn(GoogleLoginProvider.PROVIDER_ID);
  }

  signOut(): void {
    this.authService.signOut();
  }

  ngOnInit() {
    this.authService.authState.subscribe((user) => {
      this.user = user;
      this.loggedIn = (user!= null);
    })
  }

}
<p>demo works!</p>
<button type="button" (click)="signInWithGoogle()">Google</button>

<div *ngIf="user">
<img src="{{ user.photoUrl }}">
<div>
  <h4>{{ user.name }}</h4>
  <p>{{ user.email }}</p>
</div>
</div>

So what information does the socialuser hold. Lets f12 and see it.

export declare class SocialUser {
    provider: string;
    id: string;
    email: string;
    name: string;
    photoUrl: string;
    firstName: string;
    lastName: string;
    authToken: string;
    idToken: string;
    authorizationCode: string;
    response: any;
}

So a social user is able to hold the above info. Now that we have seen how to login using OAuth.

OWIN (Open Web Interface for .NET) defines a standard interface between .NET web servers and web applications.

Katana is open-source components for building and hosting OWIN-based web applications.

OAuth authorization framework enables a third-party application to obtain limited access to an HTTP Service.

To authenticate the users the server sends a signed token and this token needs to be returned to the server with each request. Some benefits of this process are

  • Scalability of Servers
  • Loosely Coupled (Apps are not bound to a specific authentication mechanism.)
  • Mobile-Friendly (this doesn’t depend on cookies)
  • Security
Based Authentication

Steps for implementation:

Leave a Reply

Your email address will not be published. Required fields are marked *