For programmers, testers and tech geeks

Token Based Authentication in Asp.net Webapi with OWIN and Identity Part - 2

In previous part, I explain the difference between token and cookie based authentication, benefits of token based over cookie based authentication. In this part I will create a sample asp.net Webapi application with token base authentication code available at GitHub

Create new Asp.net Webapi project.

Update your Startup.cs file with following code : 

using System;
using Microsoft.Owin;
using Owin;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using OWinTokenAuth;

[assembly: OwinStartup(typeof(Startup))]
namespace OWinTokenAuth
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();
            ConfigureOAuth(app);
            WebApiConfig.Register(config);
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            app.UseWebApi(config);
        }

        public void ConfigureOAuth(IAppBuilder app)
        {
            var oAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/oauth/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(1),
                Provider = new SimpleAuthorizationServerProvider()
            };
            // Token Generation
            app.UseOAuthAuthorizationServer(oAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }
    }
}

Next step is to add new class SimpleAuthorizationServerProvider.cs with following code :

using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.Owin.Security.OAuth;

namespace OWinTokenAuth
{

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

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] {"*"});

            // here we need to inject our verification, get user from database with maching credientials, if found then grand access otherwise invalid grant
            if(!context.UserName.Equals("U") || context.Password.Equals("P"))
            {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            // you can add any possible claims here... e.g name, role, department, current status or anything
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "admin"));

            context.Validated(identity);

        }
    }
}

To authenticate and authorize ( add claims ) a user can login by POST call using endpoint i.e. yourwebsite/oauth/token with parameters i.e. 'grant_type':'password' , 'username':'your username','password':'user password' .
Login call will be redirected to GrantResourceOwnerCredentials function in provider class , where we need to add logic for verify user ( authentication ) from database and we can add as much claims for this user as required for authorization.

Another important setting is token expiration time i.e. AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(1) as mention in Startup.cs class. After login token will be valid till that time span and after expiration we need to login again.

In next part I will demonstrate the client application which will used token api for authentication and also will use postman for verification. You can find all code repositories for sample applications here on GitHub https://github.com/codenbit