HI WELCOME TO SIRIS

React js or react-native with Asp.net Web API – User Registration, Login and Logout Operations part2

Leave a Comment

Create Web API Project

To create the Web API Project,Open your Visual Studio. In-order to create a new project, go to FILE > New > Project (Ctrl + Shift + N).
Image Showing Creation Of Asp.Net MVC Project
Then select Web API template. then Click On Change Authentication and Make sure that we have selected No Authentication Option.
Select MVC Template
So here we have created a brand new Web API Project.

Add Asp.Net Identity to Asp.Net Application

Asp.Net Identity is a membership system for Asp.Net Applications. It provides lot of feature like User Management, Role Management, User Authentication and Authorization, Social Logins with Facebook, gmail, twitter etc. In this article, we will use Asp.net Identity  to store user details inside Identity tables.
First of install required package for Asp.Net Identity. Right click on the project, then Manage NuGet Packages… , then search(Online) and Install Microsoft ASP.NET Identity EntityFramework.
Asp.Net Identity uses Code First Approach, So table structure inside the membership system is already defined, if you want to customize the structure, we have to do some additional works. First of all add IdentityModels file inside Models folder as follows.
ApplicationUser  class is inherited from IdentityUser. In IdentityUser class, Asp.Net Identity defined the default properties for Identity table (like Username,Email, PasswordHash etc). Inside ApplicationUser  class we have added additional two properties to User details table – FirstName and LastName.

Configure DB Connection

Inside IdentityModels.cs file, we have ApplicationDbContext class which inherits IdentityDbContext class from Asp.Net Identity. With the class constructor, we have configured the DB connection. as part of that we have to add DB connection string  in Web.config file with DefaultConnection name as follows.
This connection string will be used for Asp.Net Identity Code First Approach With UserDB Database. You can use all of your application data along Identity table inside this same database or you can have a separate DB for Application Data (Data except User Management and Role Management), in that case you may have to add one more connection string.
Back to ApplicationDbContext class, there we have overridden OnModelCreating from Asp.Net Identity to change the default identity table names.
Now in-order to see these changes in action. Go to Tools > Library Package Manager > Package Manager Console.
In code first application, Database table structure are defined in C# code, in-order to see them as database objects first of all we have to enable migration for that execute following Command.
then add a migration –  it’s like restore point in windows
to see these changes in database, execute following update command
Now if you check the database as per web config connection string you can see tables from Asp.Net Identity with our customization.

Add Web API Controller for User Registration

Now let’s add Web API controller for user registration. Right click on Controllers folder, Add > Controller. I’ll name this controller as AccountController. Inside the controller we need a Web API method Register to Post registration data from Angular 5 application. Finally the controller will be as follows.
As per Asp.Net Identity, Password should be at least 6 characters long. Inside the method we reduced minimum number of characters to 3. As a parameter for this we an object of AccountModel class. So let’s add this class inside Models Folder.
So here we have done with this Web API Project.

But there is a Problem – CORS

CORS (Cross-Origin Resource Sharing) : it is a mechanism to let a user agent (browser) gain permission to access selected resources from a server on a different origin (domain) than the site currently in use. cross-origin HTTP request occurs when it requests a resource from a different domain, protocol, or port than the one from which the current document originated.
In this application, our web API project will block request from angular 5 application, since they are cross-origin HTTP request(from different port number – 4200). In-order to allow cross-origin HTTP request, we have to configure Web API project for this localhost:4200 request. so let’s look how we can do that.
First of we have to install NuGet Package : WebApi.Cors. Back to Visual Studio, Select your Web API project from solution explorer, then go to Tools > Library Package Manager > Package Manager Console. use following NuGet command to install WebApi.Cors.
Now let’s look how we can use this package. In-order allow cross-origin request in Web API project, Go to App_Start >WebApiConfig.cs file. add following lines of code
now web API project is ready for cross-origin request from our angular 5 application.
Now try run this application without debug mode, some of you may get this problem.
Could not load file or assembly System.Web.Http
It is due to different version of latest WebApi.Cors and System.Web.Http (5.0.0), so lets install same version of WebApi.Core (Not Cors it is Core). it will resolve this assembly problem. for that you can run following NuGet Command from Package Manager Console.
So here we have successfully implemented React User Registration with Web API.

Token Based User Authentication in Web API

Now let’s update the Web API Project for Token Based Authentication. In-order to implement user authentication we need OWIN(Open Web Interface For .Net Applications). It act as a middle-ware between Asp.Net Application and IIS Server. First of all install required NuGet Packages.
In Solution explorer, Right Click On References. then click on Manage NuGet Packages. then do an online search for following packages and install them.
  • Microsoft ASP.NET Identity Owin
  • Microsoft.Owin.Host.SystemWeb
  • Microsoft.Owin.Cors
In-order to work with OWIN, we have to create OWIN Startup class. For that right click on Project > New Item,  then Search for OWIN Startup class. and I’ll name the file as Startup.cs. Now you can update the class as follows.
Let’s discuss line by line.
app.UseCors  function will enable CORS(Cross Origin Resource Sharing) inside the application. In previous article, we already enabled CORS in WebApiConfig.cs file. Now you can comment that line.
After Enabling CORS, we have an object of OAuthAuthorizationServerOptions. inside that we have following properties
  • TokenEndpointPath  – Specifies URL to Authenticate a user. In this Case we have to make HttpPost Request with username and password into http:localhost:portnumber/token URL. If given user credentials are valid, it will return an access token.
  • Provider – we set provider as ApplicationOAuthProvider class object. inside that we define how do we authenticate a user from database.
  • AccessTokenExpireTimeSpan  – access token from token request response will have an expire time. In this case it is 60 minutes/1 Hour.
  • AllowInsecureHttp – flag to secure token request from unsecured HTTP.
Let’s create the ApplicationOAuthProvider provider class to  validate username and password.
ApplicationOAuthProvider is inherited from OAuthAuthorizationServerProvider class. Inside that we have overridden two functions.
  • ValidateClientAuthentication() – used to validate client device based on clientID and secret code. but in this project we’ll not authenticate client device.
  • GrantResourceOwnerCredentials() – authenticate a user with given username and password. If authentication is successful then we save user details as Claims Identity. It can be used to retrieve user details without DB interaction.
Now back to VS Code Editor. Let’s make token POST request on login form submission.

Consume Web API Methods with Authorization

To consume Web API method with Authorize Attribute, we need to send access token along with the request. To demonstrate this process, let me add a Web API method with Authorize attribute.
Inside the Web API project, I’ll add a new Web API method inside AccountController as follows.
This method returns few user claims saved during user authentication.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.