Token Based Authentication in Asp.net MVC Web Api

Token Based Authentication in Asp.net MVC Web API





1) You Can Use It Either New Project Or 
2) You can use It with New Project 
  
Procedure Is Same For Both Type of Project . Now I am Not Going too Deep Just Impliment Code and there Requirements . Lets Start including some packages from nuget and used with Some Custom Class Step By Step

1) . Firstly You Need To Install Three Package Of Owin 

  1. Microsoft.Owin.Host.SystemWeb
  2. Microsoft.Owin.Security.OAuth
  3. Microsoft.Owin.Cors
After Installing Packages From Nuges You need To write Some class And There Code Like this 

2). Create Class "AuthorizeAttribute.cs" with Right Click on Project



using System;

using System.Collections.Generic;

using System.Linq;
using System.Web;

namespace MYProject
{
    public class AuthorizeAttribute : System.Web.Http.AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
            {
                base.HandleUnauthorizedRequest(actionContext);
            }
            else
            {
                actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Forbidden);
            }
        }
    }
}



3). Now Create Another Custom Class With any name Like "MyAuthorizationServerProvider"


using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OAuth;
using MYProject.Common;
using MYProject.DataEntity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;

namespace  MYProject
{
    public class MyAuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        //public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        //{
        //   context.Validated(); // 
        //}
        PowerHMSEntities db = new PowerHMSEntities();
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            if (context.ClientId == null)
                context.Validated();

            return Task.FromResult<object>(null);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            string username = context.UserName, Password = GetSHA1HashData(context.Password);

            if (Membership.ValidateUser(username,Password))
            {
                var user = db.UserDetails.Where(c => (c.UserName == username || c.EmailID == username) && c.Password == Password && c.IsActive.Value.Equals(true)).FirstOrDefault();
                FormsAuthentication.SetAuthCookie(context.UserName.Trim(), false);
                identity.AddClaim(new Claim(ClaimTypes.Sid, Convert.ToString(user.UserID)));
                identity.AddClaim(new Claim("username", user.UserName));
                identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
                var properties = CreateProperties(user.UserName);
                var ticket = new AuthenticationTicket(identity, properties);
                context.Validated(ticket);
            }
           
            else
            {
                context.SetError("invalid_grant", "Provided username and password is incorrect");
                return;
            }
        }
        #region[TokenEndpoint]
        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);
        }
        #endregion

        #region[CreateProperties]
        public static AuthenticationProperties CreateProperties(string userName)
        {
            IDictionary<string, string> data = new Dictionary<string, string>
            {
                { "userName", userName }
            };
            return new AuthenticationProperties(data);
        }
        #endregion

 public static string GetSHA1HashData(string data)
        {
            var sha1 = SHA1.Create();
            byte[] hashData = sha1.ComputeHash(Encoding.Default.GetBytes(data));
            var returnValue = new StringBuilder();
            foreach (var t in hashData)
            {
                returnValue.Append(t.ToString());
            }
            return returnValue.ToString(); // return hexadecimal string

        }
    }
}


3). Now You Need Owin Startup Class

using System;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using Owin;

[assembly: OwinStartup("MYProjectStartup", typeof(MYProject.Startup))]

namespace MYProject
{
    public class Startup
    {
        public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888



            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
            //enable cors origin requests
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            var myProvider = new MyAuthorizationServerProvider();
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = myProvider
            };
            app.UseOAuthAuthorizationServer(options);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());


            HttpConfiguration config = new HttpConfiguration();
            WebApiConfig.Register(config);
        }
    }
}

4). some Time Its Create Issue You Need To Update "newtonsoft.json" Dll file from Nuget



5). And Some Time You Need to  "Startup.cs" class in  "web config " 

 <appSettings>
  <add key="owin:appStartup" value="MYProjectStartup" />  
  </appSettings>


6). also Need to Update  "WebApiConfig" class 

here Register "AuthorizeAttribute" class like this 
   config.Filters.Add(new AuthorizeAttribute());  

example:- 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace MYProject
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services           
            // Web API routes
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
            name: "CommonApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            // routeTemplate: "api/{controller}/{id}",
            defaults: new { controller = "Common", id = RouteParameter.Optional }
        );
            config.Routes.MapHttpRoute(
               name: "DefaultApi",
               //routeTemplate: "api/{controller}/{id}",
               routeTemplate: "api/{controller}/{id}",
               defaults: new { id = RouteParameter.Optional }
           );
            config.Filters.Add(new AuthorizeAttribute());
            config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;        
        }

        public static void Register(object configuration)
        {

            throw new NotImplementedException();
        }
    }

}


7). Now You Can Check Your Api With Postman Get Token





8). Use Api Token With Post Man


No comments:

Post a Comment

Thank You For Your Great Contribution

Featured Post

how to find n number of nodes have child or cildren

 how to find n number of nodes have child or cildren for that we use recursive function  const   data = {     'id' : '0' ,...

Popular Posts