Web API Token Based Authentication using Microsoft OWIN

Uppili Vasanthi
Jul 8 · 5 min read
Fig: Control Flow of Token based Authentication
public void Configuration(IAppBuilder app)
// For more information on how to configure your application, //visit http://go.microsoft.com/fwlink/?LinkID=316888
OAuthAuthorizationServerOptions option = new OAuthAuthorizationServerOptions

TokenEndpointPath = new PathString("/token"),
Provider = new ApplicationAuthProvider(), AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),
AllowInsecureHttp = true
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
Fig: Startup.cs class
[EnableCors(origins: "*", headers: "*", methods: "*")]public class ApplicationAuthProvider : OAuthAuthorizationServerProvider
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
AuthRepository authRepository = new AuthRepository();
bool Valid = authRepository.ValidateUser(context.UserName,
if (Valid)
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("Username", context.UserName));
identity.AddClaim(new Claim("Password", context.Password));
context.SetError("invalid_grant", "The user name or password is incorrect.");
Fig: ApplicationAuthProvider.cs
[Authorize]public class ClientsController : ApiController
MTLLCEntities db = new MTLLCEntities();
#region Get Clients
public IHttpActionResult GetAllClients()
Fig: Testing the API Call
Fig: Generating Access Token
Fig : Output Screen

Uppili Vasanthi

Written by

Associate Trainee- MouriTech

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade