You are here:   Blog
Register   |  Login

 

Jan 15

Written by: Michael Washington
1/15/2017 3:04 PM  RssIcon

You can authenticate a user in an ASP.NET 4.5 application directly from an Angular 2+ application log in page.

This is an improvement over previous articles such as: Implement ASP.NET 4 MVC Application Security in Angular 2 Using OData 4 that required the user to navigate away from the Angular application and log in using a normal ASP.NET MVC page and then reload the Angular application.

image

To demonstrate this, we will start with the code from the article: Implement ASP.NET 4 MVC Application Security in Angular 2 Using OData 4.

Install The NuGet Package

image

We first need to install the Nuget Package: Microsoft.AspNet.WebApi.Owin.

This will allow access to the ApplicationSignInManager from a WebAPi method.

Open the NuGet Package Manger Console.

image

Enter:

Microsoft.AspNet.WebApi.Owin
…and press Enter.

The package will install.

Create The Data Transfer Object (DTO)

image

We will now create a Data Transfer Object (DTO) to pass the user authentication parameters between the Angular code and the server side code.

Create a class file, DTOAuthentication.cs using the following code:

 

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Angular2QuickStart.Models
{
    public class DTOAuthentication
    {
        [Key]
        public string UserName { get; set; }
        public string Password { get; set; }
    }
}

 

Create The Controller

image

We will now create the server side code that the Angular code will communicate with to log the user into the application.

Create a class file, Angular2AuthenticationController.cs using the following code:

 

using Angular2QuickStart.Models;
using Microsoft.AspNet.Identity.Owin;
using System.Net.Http;
using System.Web.Http;
namespace Angular2QuickStart.Controllers
{
    public class Angular2AuthenticationController : ApiController
    {
        // ********************************************************
        // Angular2Login
        private ApplicationSignInManager _signInManager;
        public ApplicationSignInManager SignInManager
        {
            get
            {
                // You need to install nuget packag: Microsoft.AspNet.WebApi.Owin
                // for the line below to work
                return _signInManager ?? 
                    Request.GetOwinContext().Get<ApplicationSignInManager>();
            }
            private set
            {
                _signInManager = value;
            }
        }
        // POST: /Account/Angular2Login
        #region public ActionResult Angular2Login(DTOAuthentication Authentication)
        [HttpPost]
        [AllowAnonymous]
        public IHttpActionResult Angular2Login(DTOAuthentication Authentication)
        {
            string strResult = "";
            // Get values passed
            var paramUserName = Authentication.UserName;
            var paramPassword = Authentication.Password;
            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, 
            // change to shouldLockout: true
            var result = SignInManager.PasswordSignIn(
                paramUserName, paramPassword, false, shouldLockout: false);
            switch (result)
            {
                case SignInStatus.Success:
                    strResult = "Success";
                    break;
                case SignInStatus.LockedOut:
                    strResult = "LockedOut";
                    break;
                case SignInStatus.RequiresVerification:
                    strResult = "RequiresVerification";
                    break;
                case SignInStatus.Failure:
                default:
                    strResult = "Failure";
                    break;
            }
            return Ok(strResult);
        }
        #endregion
    }
}

 

The Angular Code

image

We will use Angular Dynamic (Reactive) Forms to gather the login information.

This will provide validation and allow the user to press the Enter button to submit the form.

image

To enable Angular Dynamic (Reactive) Forms, add:

import { ReactiveFormsModule } from '@angular/forms';

and:

ReactiveFormsModule

…to the app.module.ts file.

image

We will now create a TypeScript interface to pass the user authentication parameters between the Angular code and the server side code.

Create a TypeScript file, authentication.ts using the following code:

 

/* Defines the Authentication entity */
export interface IAuthentication {
    UserName: string;
    Password: string;
}

 

image

We now need to create the service method that will communicate with the server side code.

Open the user.service.cs file and add the following import for the IAuthentication interface we just added:

 

import { IAuthentication } from './authentication';

 

Also, add the following method to the same file:

 

    loginUser(Authentication: IAuthentication): Observable<string> {
        var Url = 'api/Angular2Authentication';
        // This is a Post so we have to pass Headers
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        // Make the Angular 2 Post
        return this._http.post(Url, JSON.stringify(Authentication), options)
            .map((response: Response) => <string>response.statusText)
            .do(data => console.log('loginUser: ' + JSON.stringify(data)))
            .catch(this.handleError);
    }

 

This method takes the username and password and passes it to the Angular2AuthenticationController (created earlier) that logs the user in.

image

Next, open the user.component.html file and add the following code to create the form:

 

<div *ngIf='!loggedIn'>
    <form [formGroup]="loginForm" (ngSubmit)="logIn($event)">
        <input formControlName="email"
               type="email" placeholder="Your email">
        <br />
        <input formControlName="password"
               type="password" placeholder="Your password">
        <br />
        <button type="submit">Log in</button>
    </form>
</div>

 

image

Finally, to complete the code, add the following imports to the user.component.ts file:

 

import { FormBuilder, Validators } from '@angular/forms';
import { IAuthentication } from './authentication';

 

Then add the following properties:

 

    loggedIn: boolean = false;
    public loginForm = this.fb.group({
        email: ["", Validators.required],
        password: ["", Validators.required]
    });

 

Alter the constructor to the following (to inject the Angular FormBuilder):

 

    constructor(
        private _userService: UserService,
        public fb: FormBuilder) {
    }

 

Add the following line to the getCurrentUser() method:

 

this.loggedIn = (this.user.UserName !== "[Not Logged in]");

 

Lastly, add the following method to pass the username and password to the service, and then call the getCurrentUser() method to see if if login was successful:

 

    logIn() {
        // Get the form values
        let formData = this.loginForm.value;
        let email = formData.email;
        let password = formData.password;
        let Authentication: IAuthentication = {
            UserName: email,
            Password: password
        };
        // Call the service
            this._userService.loginUser(Authentication).subscribe(
                response => {
                    // Call the method to see who 
                    // the server-side OData code 
                    // thinks is logged in
                    this.getCurrentUser();
            },
            error => this.errorMessage = <any>error);
    }

 

Angular 2 Tutorial Series

  1. Hello World! in Angular 2 using Visual Studio 2015 and ASP.NET 4
  2. Implement ASP.NET 4 MVC Application Security in Angular 2 Using OData 4
  3. Tutorial: Creating An Angular 2 CRUD Application Using MVC 5 and OData 4
  4. Tutorial: An End-To-End Angular 2 Application Using MVC 5 and OData 4

Resources to Learn Angular 2

Angular 2: Getting Started (Pluralsight – Paid)

Introduction to Angular 2.0 (Microsoft Virtual Academy – Free)

Getting Started with npm in Visual Studio

Using EcmaScript 2015 Modules in TypeScript with SystemJS

Download

The project is available at http://lightswitchhelpwebsite.com/Downloads.aspx

You must have Visual Studio 2015 Update 3 (or higher) and TypeScript 2.0 (or higher) installed to run the code.

Tags:
Categories:
Microsoft Visual Studio is a registered trademark of Microsoft Corporation / LightSwitch is a registered trademark of Microsoft Corporation