Monday 27 March 2017

Owin Step By Step Token Based Authentication Using ASP.Net Web API

Step By Btep to Token Based Authentication Using ASP.Net Web API, OWIN




  • Step-1: Add webApi Project in visual studio 2015
  • Step-2: Setup the connection string in config file
  • Step-3: Add User class with Get and Set property
  • Step-4: Add AppDataConetext class file and add required method to validate user and get user details
  • Step-5: Add ApiController and add required method
  • Step-6: Change your ApplicationOAuthProvider.cs file
  • Step-7: Update ApplicationOAuthProvider.cs file


  • Add one more project to test your WebApi project with OWIN Authentication


  • Step-8: just add only 1 html file and required css and JS file.

  • Here I will explain how to Implement Token Based Authentication Using ASP.Net Web API and ajax post as client side. This is very important to implement Token Based Authentication in Web api project to security. Here I explained step by step to implement Token Based Authentication Using ASP.Net Web API. Try this and get security in your data. In previously I explained about Create Chat application in asp.net And Three tier architecture in asp.net For more example javascript and Asp.net


    Searches related to owin authentication web api example
    web api token based authentication example
    owin bearer token authentication with web api sample
    token based authentication using asp.net web api 2 owin and identity
    web api security token example
    web api token based authentication example c#
    Securing ASP.NET Web API using Token Based Authentication
    Implement Token Based Authentication Using ASP.Net Web API and ajax post as client side
    Implement Token Based Authentication with 2 separate project with custom table as login details and Authentication user
    Owin Step By Step Token Based Authentication Using ASP.Net Web API
    Token Based Authentication Using ASP.Net Web API, OWIN

    Now follow these step to security your web api with OWIN.

    Step-1. Add webApi Project in visual studio 2015

    Add webApi Project in visual studio 2015 and setup the name

    Step-2. Setup the connection string in config file

    You must be Setup the connectionstring in config file for database operation and user validate method

    Step-3. Add User.cs class with Get and Set property


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace API.Models
    {
        public class User
        {
            public int Id { get; set; }
            public string UserName { get; set; }
            public string Password { get; set; }
            public string Name { get; set; }
            public string MobileNo { get; set; }
            public string EmailId { get; set; }
            public string Country { get; set; }
            public string Address { get; set; }
            public string Hobbies { get; set; }
            public byte Gender { get; set; }
            public DateTime DateOfBirth { get; set; }
            public string BirthDate { get; set; }
            public string CountryName { get; set; }
            public string Search { get; set; }
            public string UserIds { get; set; }
      
    
            public string AuthenticationKey { get; set; }
        }
    }
    

    Step-4. Add AppDataConetext.cs file to database operation


    using System.Linq;
    
    using System.Data.Entity;
    
    namespace API.Models
    {
        public class AppDataConetext : DbContext
        {
    
            public AppDataConetext()
            :base("name=Conn")
            {
            }
    
            
            public User validateUser(string UserName,string Password)
            {
                User list = new User();
                list = Database.SqlQuery<User>("EXEC [ValidateUser] {0}, {1}", UserName, Password).FirstOrDefault();
                return list;
            }
            public User getUserById(int Id)
            {
                User list = new User();
                list = Database.SqlQuery<User>("EXEC [getUserById] {0}", Id).FirstOrDefault();
                return list;
            }
          
        }
    }
    

    Step-5. Add WebAPIController.cs and add required action method


    using API.Models;
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.EntityFramework;
    using Microsoft.AspNet.Identity.Owin;
    using Microsoft.Owin.Security;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Security.Claims;
    using System.Security.Cryptography;
    using System.Threading.Tasks;
    using System.Web;
    using System.Web.Http;
    using System.Web.Http.Cors;
    
    namespace API.Controllers
    {
        //[EnableCors(origins: "*", headers: "*", methods: "*")]
        //[Authorize]
        public class WebAPIController : ApiController
        {
            private const string LocalLoginProvider = "Local";
    
            AppDataConetext Db = new AppDataConetext();
    
            private IAuthenticationManager Authentication
            {
                get { return Request.GetOwinContext().Authentication; }
            }
    
            [Authorize]
            [ActionName("getUserById")]
            [EnableCors(origins: "*", headers: "*", methods: "*")]
            [System.Web.Http.HttpPost]
            public User getUserById([FromBody]User objUser)
            {
                User list = new User();
                list = Db.getUserById(Convert.ToInt32(objUser.Id));
                return list;
            }
    
            [Authorize]
            [ActionName("keyStatus")]
            [EnableCors(origins: "*", headers: "*", methods: "*")]
            [System.Web.Http.HttpPost]
            public string keyStatus()
            {
               return "Ok";
            }
        }
    }
    

    Step-6. Change your ApplicationOAuthProvider.cs file like this


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Security.Claims;
    using System.Threading.Tasks;
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.EntityFramework;
    using Microsoft.AspNet.Identity.Owin;
    using Microsoft.Owin.Security;
    using Microsoft.Owin.Security.Cookies;
    using Microsoft.Owin.Security.OAuth;
    using API_OwinDemo.Models;
    using API.Models;
    
    namespace API_OwinDemo.Providers
    {
        public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
        {
            private readonly string _publicClientId;
    
            public ApplicationOAuthProvider(string publicClientId)
            {
                if (publicClientId == null)
                {
                    throw new ArgumentNullException("publicClientId");
                }
    
                _publicClientId = publicClientId;
            }
    
            public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
            {
                //var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
    
                //ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
    
                //if (user == null)
                //{
                //    context.SetError("invalid_grant", "The user name or password is incorrect.");
                //    return;
                //}
    
                //ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
                //   OAuthDefaults.AuthenticationType);
                //ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                //    CookieAuthenticationDefaults.AuthenticationType);
    
                //AuthenticationProperties properties = CreateProperties(user.UserName);
                //AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
                //context.Validated(ticket);
                //context.Request.Context.Authentication.SignIn(cookiesIdentity);
    
                bool isValidUser = false;
                context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
    
                if (context.UserName == "test" && context.Password == "test")
                {
                    isValidUser = true;
                }
                User list = new User();
                AppDataConetext Db = new AppDataConetext();
                list = Db.validateUser(context.UserName, context.Password);
                if (list != null)
                {
                    isValidUser = true;
                }
    
                if (!isValidUser)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
    
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim("sub", context.UserName));
                identity.AddClaim(new Claim("role", "user"));
    
                context.Validated(identity);
            }
    
            public override Task TokenEndpoint(OAuthTokenEndpointContext context)
            {
                foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
                {
                    context.AdditionalResponseParameters.Add(property.Key, property.Value);
                }
    
                return Task.FromResult<object>(null);
            }
    
            public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
            {
                // Resource owner password credentials does not provide a client ID.
                if (context.ClientId == null)
                {
                    context.Validated();
                }
    
                return Task.FromResult<object>(null);
            }
    
            public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
            {
                if (context.ClientId == _publicClientId)
                {
                    Uri expectedRootUri = new Uri(context.Request.Uri, "/");
    
                    if (expectedRootUri.AbsoluteUri == context.RedirectUri)
                    {
                        context.Validated();
                    }
                }
    
                return Task.FromResult<object>(null);
            }
    
            public static AuthenticationProperties CreateProperties(string userName)
            {
                IDictionary<string, string> data = new Dictionary<string, string>
                {
                    { "userName", userName }
                };
                return new AuthenticationProperties(data);
            }
        }
    }
    

    Step-7. Update Your WebApiConfig.cs file like this


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Http;
    using System.Web.Http;
    using Microsoft.Owin.Security.OAuth;
    using Newtonsoft.Json.Serialization;
    using System.Web.Http.Cors;
    
    namespace API_OwinDemo
    {
        public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                //// Web API configuration and services
                //// Configure Web API to use only bearer token authentication.
                //config.SuppressDefaultHostAuthentication();
                //config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
    
                //// Web API routes
                //config.MapHttpAttributeRoutes();
    
                var cors = new EnableCorsAttribute("*", "*", "*");
                config.EnableCors();
    
                config.Routes.MapHttpRoute(
                    name: "WithActionApi",
                    routeTemplate: "api/{controller}/{action}/{id}",
                     defaults: new { id = RouteParameter.Optional }
                );
    
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
            }
        }
    }
    
    Finaly you have creted and Done with API project now create 1 html page to test your OWIN Token Based Authentication

    Step-8. Add html page to test your OWIN Token Based Authentication

    Your Html page like this
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>owin authentication web api example, Token Based Authentication Using ASP.Net Web API with Ajax, OWIN  </title>
        <link rel='stylesheet prefetch' href='http://fonts.googleapis.com/css?family=Roboto:400,100,300,500,700,900|RobotoDraft:400,100,300,500,700,900'>
        <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css'>
        <link href="Content/css/style.css" rel="stylesheet" />
        <link href="Content/css/jquery-ui.css" rel="stylesheet" />
        <script src="Content/js/jquery-1.12.4.js"></script>
        <script src="Content/js/jquery-ui.js"></script>
    </head>
    <body>
        <div class="pen-title">
            <h1> owin authentication web api example, Token Based Authentication Using ASP.Net Web API with Ajax</h1>
        </div>
        <div class="module form-module">
            <div class="form">
                <h2>owin authentication web api example Log in and validate user</h2>
                <form>
                    <input type="text" placeholder="Username" id="loginUserName" />
                    <input type="password" placeholder="Password" id="loginPassword" />
                    <button onclick="validateUser(); return false">Login</button>
                </form>
            </div>
        </div>
        <!--<script src="Content/js/jquery.min.js"></script>-->
        <script src="Content/js/index.js"></script>
        <style>
            .at-button {
            }
        </style>
        <script>
            var type = "local";
            var rootUrl = "";
    
                //Start - this is for testing only
                if (type == "local") {
                    rootUrl = "http://localhost:15489/";
                }
                else if (type == "iis") {
                    rootUrl = "http://192.168.0.179:81/";
                }
                else if (type == "sandbox") {
                    rootUrl = "";
                }
                else if (type == "live") {
                    rootUrl = "";
                }
                //End
    
            $('#loginUserName #loginPassword').keyup(function (e) {
                if (e.keyCode == 13) {
                    validateUser();
                }
            });
    
            function validateUser() {
                if ($("#loginUserName").val() == "" || $("#loginPassword").val() == "") {
                    alert('Please enter username or password');
                    return false;
                }
    
                jQuery.support.cors = true;  
    
                $.ajax({
                    url: rootUrl + "TOKEN",
                    crossDomain: true,
                    method: "POST",
                    dataType: "json",
                    data: $.param({ grant_type: 'password', username: $('#loginUserName').val(), password: $('#loginPassword').val() }),
                    //contentType: "application/json;",
                    //headers: { 'Content-Type': 'application/x-www-form-urlencoded', "X-Custom-Header": "*" },
                    //headers: {  'X-Custom-Header' },
                    //headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': '*' },
                    //headers: {'Content-Type': 'Access-Control-Request-Headers','X-Custom-Header','application/x-www-form-urlencoded', "X-Custom-Header": "33" },
                    //headers: { "X-Octopus-ApiKey": "API-xxxxxxxxx" },
                    success: function (data) {
                        if (data != null) {
                            localStorage.setItem('accessToken', data.access_token);
                        }
                        else if (data.error_description != null)
                        {
                            alert(data.error_description);
                        }
                        else {
                            alert('Username or password is wrong');
                        }
                    },
                    error: function (jqxhr) {
                        alert('Username or password is wrong');
                    }
                });
                return false;
            }
            function getUserById(Id) {
                var headers = {};
                headers = getHeaders();
                var UserData =
                {
                    Id: Id
                };
                $.ajax({
                    type: "POST",
                    crossDomain: true,
                    data: JSON.stringify(UserData),
                    url: rootUrl + "api/WebAPI/getUserById",
                    dataType: "json",
                    contentType: "application/json",
                    headers: headers,
                    success: function (data) {
                        $('#UserName').val(data.UserName);
                        $('#Password').val(data.Password);
                    },
                    error: function (jqXHR, status, text) {
                        keyIsExpired(jqXHR, status, text);
                    }
                });
            }
            function openRegister() {
                $('#btnRegister').click();
            }
            function keyIsExpired(jqXHR, status, text) {
                localStorage.setItem('accessToken', '');
                if (jqXHR.status == 500) {
                    // Server side error
                } else if (jqXHR.status == 302 || jqXHR.status == 404 || jqXHR.status == 401) {
                    alert('Authantication key is expired, required login to continue...');
                    window.location.href = "login.html";
                }
            }
            function getHeaders() {
                var token = localStorage.getItem('accessToken');
                var headers = {};
                if (token) {
                    headers.Authorization = 'Bearer ' + token;
                }
                if (token == null || token == "") {
                    window.location.href = "loginRegister.html";
                }
                return headers;
            }
            function getParameterByName(name, url) {
                if (!url) {
                    url = window.location.href;
                }
                name = name.replace(/[\[\]]/g, "\\$&");
                var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
                    results = regex.exec(url);
                if (!results) return null;
                if (!results[2]) return '';
                return decodeURIComponent(results[2].replace(/\+/g, " "));
            }
    
            $(document).ready(function () {
                var Id = getParameterByName('id');
                if (Id != null && Id != "") {
                    var token = localStorage.getItem('accessToken');
                    if (token == null || token == "")
                    {
                        window.location.href = "loginRegister.html";
                    }
                    else
                    {
                        //keyStatus();
                        getUserById(Id);
                        $('#Password').hide();
                        $('#Id').val(Id);
                        $("#btnRegisterUpdate").html('Update');
                    }
                }
            });
        </script>
    </body>
    </html>
    
    Now You are complete done with Token Based Authentication OWIN example, first build the webApi project and run it. and then run html page and login.

    No comments:

    Post a Comment



    Asp.net tutorials