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
app.UseCors(CorsOptions.AllowAll);
OAuthAuthorizationServerOptions option = new OAuthAuthorizationServerOptions
{

TokenEndpointPath = new PathString("/token"),
Provider = new ApplicationAuthProvider(), AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),
AllowInsecureHttp = true
};app.UseOAuthAuthorizationServer(option);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
Fig: Startup.cs class
[EnableCors(origins: "*", headers: "*", methods: "*")]public class ApplicationAuthProvider : OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
AuthRepository authRepository = new AuthRepository();
bool Valid = authRepository.ValidateUser(context.UserName,
context.Password);
if (Valid)
{
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("Username", context.UserName));
identity.AddClaim(new Claim("Password", context.Password));
context.Validated(identity);
}
else
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}}}
Fig: ApplicationAuthProvider.cs
[Authorize]public class ClientsController : ApiController
{
MTLLCEntities db = new MTLLCEntities();
#region Get Clients
[HttpGet]
[Route("api/GetClients")]
public IHttpActionResult GetAllClients()
{
//Logic
}
}
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