Secured Token Based WebAPI with custom authentication

Hi Guys,

I had a requirement to create Secured  Token Based WebAPI which can be consumed using mobile applications. And it had to check a custom authentication stored in database. Upon successful login an auth token would be returned subsequent requests must pass this auth token to get data.

Reference : http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/



1) Create a WebAPI Project as following




















2) Modify the Startup.cs as following

using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;

[assembly: OwinStartup(typeof(SecuredWebAPI.Startup))]
namespace SecuredWebAPI
{
    public class Startup
    {
        public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

        public static string PublicClientId { get; private set; }

        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();
            ConfigureOAuth(app);
           
            WebApiConfig.Register(config);
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            app.UseWebApi(config);
        }

        public void ConfigureOAuth(IAppBuilder app)
        {
            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new SimpleAuthorizationServerProvider()

               
            };

         

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

         

     

  }

    }
}


3) Modify the SimpleAuthorizationServerProvider.cs with the following


using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security.OAuth;
using System;
using System.Security.Claims;
using System.Threading.Tasks;

namespace SecuredWebAPI
{
    public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            //Your authentication logic here
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

         

            int userId = -1;
            BE.ReturnDataMsg<Guid> objReturnLoginDataMsg = null;

            bool mustChangePwd;
            string name;
            objReturnLoginDataMsg =
                BusinessLayer.Services.UserService.Login(context.UserName, context.Password,
                1, true, out mustChangePwd, out name, out userId, true);

            if (objReturnLoginDataMsg.Status == BE.ProcessStatus.Successful ||
                    objReturnLoginDataMsg.Status == BE.ProcessStatus.SuccessButExpired)
            {

                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim("sub", context.UserName));
                identity.AddClaim(new Claim("loginKey", objReturnLoginDataMsg.Data.ToString()));
                context.Validated(identity);


            }

            else
            {
                context.SetError("invalid_grant", objReturnLoginDataMsg.Message);
                return;

               

            }              

        }    

    }
}





Comments