Login and Logout With Web API using Token Based Authentication

ASHOK CHAUDHARY
3 min readJan 28, 2019

Introduction :

In this topic we will discuss about the login and logout with web api using token based authentication.

The Basic Steps are:

i) Angular 7 login and logout with web API token based authentication

ii) Design Login form

iii) web API token based authentication using OWIN and asp.net identity

At First we should have to create one web API project

Create a class like below :

namespace Webapi.models

{

Public class User

{

[key]

public int Id {get; set;}

[Required MinLength(3), MaxLength(50)]

public string UserName {get; set;}

[Required , MinLength(3) , MaxLenth(50)]

public string Password {get; set;}

}

}

Now, install following packages in your web api project

Microsoft.OwinMicrosoft.Owin.Host.SystemWebMicrosoft.Owin.Security.OAuthMicrosoft.Owin.SecurityMicrosoft.AspNet.Identity.OwinMicrosoft.Owin.Cors

Steps: Right click on project and Select manage Newget Packages For Solution.

In search option , search the following packages as above .

The provider class like this :

using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OAuth;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web.Http.Cors;
using DeepCart.Models;
using System;
namespace Webapi.DtProvider { [EnableCors(origins: "*", headers: "*", methods: "*")]
public class DotNetTechyAuthServerProvider: OAuthAuthorizationServerProvider {
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) {
context.Validated();
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) {
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new [] {
"*"
});
using(var db = new WebapiContext()) {
if (db != null) {
var user = db.Registrations.ToList();
if (user != null) {
if (!string.IsNullOrEmpty(user.Where(u => u.UserName == context.UserName && u.Password == context.Password).FirstOrDefault().UserName)) {
var currentUser = user.Where(u => u.UserName == context.UserName && u.Password == context.Password).FirstOrDefault();
identity.AddClaim(new Claim("Role", currentUser.Role));
identity.AddClaim(new Claim("Id", Convert.ToString(currentUser.Id)));
var props = new AuthenticationProperties(new Dictionary < string, string > {
{
"DisplayName",
context.UserName
},
{
"Role",
currentUser.Role
}
});
var ticket = new AuthenticationTicket(identity, props);
context.Validated(ticket);
} else {
context.SetError("invalid_grant", "Provided username and password is not matching, Please retry.");
context.Rejected();
}
}
} else {
context.SetError("invalid_grant", "Provided username and password is not matching, Please retry.");
context.Rejected();
}
return;
}
}
}
}

It has two basic methods which needs to be overridden in order to validate user name and password from your database and return the token back if username and password is valid.

First method is : ValidateClientAuthentication

Second Method is: GrantResourceOwnerCredentials

Now we should create a class called Startup like below:

using Webapi.DtProvider;using Microsoft.Owin;using Microsoft.Owin.Cors;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(Webapi.Startup))]
namespace Webapi{
// public class Startup { public void ConfigureAuth(IAppBuilder app) { app.UseCors(CorsOptions.AllowAll);
var OAuthOptions = new OAuthAuthorizationServerOptions {
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(20),
Provider = new DotNetTechyAuthServerProvider()
}; app.UseOAuthBearerTokens(OAuthOptions);
app.UseOAuthAuthorizationServer(OAuthOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
} public void Configuration(IAppBuilder app) {
//app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
ConfigureAuth(app);
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
}

After that we can test using Postman , access token Generation.

Now, we can integrate this access token in angluar 7

Steps :

  1. Create a service to call the we API get the token back.
  2. Store the token for next request to pass into header
  3. Call the validate user method from login button click event
  4. Create a auth guard and override can activate method

Service Method:

ValidateUser(user: any){ var userData = "username=" + user.UserName + "&password=" + user.Password + "&grant_type=password"; var reqHeader = new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded',
'No-Auth': 'True'
});
return this.httpClient.post(this.apiURL + '/token', userData, {
headers: reqHeader
})
.pipe(
map(res => res),
catchError(this.errorHandler)
);
}

Auth Guard:

canActivate(): boolean { if (!this.auth.isAuthenticated()) {  //this.router.navigate(['login']);  console.log('You are not authrised to view this page')  return false; } return true;}store token in local storagestoreToken(token: string) { localStorage.setItem("token", token);}

Once login is success we should call to Token Method.

--

--