Introduction
This tutorial is divided into two parts. In the first part (this one), we will develop our Web API and secure the Web API using OAuth 2.0. In the second part, we will develop the front-end Angular app to consume the Web API.
The project code files, database backup, and database script are attached with this article or you can download these from this link to Project Source Code.
How will it work?
The first time a user requests the token and passes the credentials for that, we will create a Provider class which receives that HTTP request and validates the credentials. If the credentials are correct, it will register the user and will generate a specific token against this request and pass back to the client. Now, the client will receive this token and will store for the next HTTP request. When a client will request for a resource, it will pass this token into the headers of the HTTP request.
Start with the creation of a database with the name OauthDb, containing two tables - User and Product.
User Table

Product Table
Step 1
Create an ASP.NET project with the name WebAPI_Oauth.

Select Web API

Step 2
Add the following NuGet packages
- Microsoft.Owin
- Microsoft.Owin.Host.SystemWeb
- Microsoft.Owin.Security.OAuth
- Microsoft.Owin.Security
- Microsoft.AspNet.Identity.Owin
- Microsoft.Owin.Cors
Add Entity Model.

Step 4
Add a new folder with the name "Provider" and inside the folder, add new a class OauthProvider.cs.

OauthProvider.cs
- using Microsoft.Owin.Security.OAuth;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Security.Claims;
- using System.Threading.Tasks;
- using System.Web;
- using WebAPI_Oauth.Models;
- namespace WebAPI_Oauth.Provider
- {
- public class OauthProvider : OAuthAuthorizationServerProvider
- {
- public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
- {
- //First request will come here, this method will validate the request wheather it has crendtials(UserName and Password) if the request not contain username and
- //password the request will reject from here not proceded any further
- context.Validated();
- }
- public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
- {
- //If the request has valid and it contain username and password than this method will check correct crenstials and than generate a valid token
- var identity = new ClaimsIdentity(context.Options.AuthenticationType); //it will check the authenticate type
- using (var db = new DataContext())
- {
- if (db != null)
- {
- var user = db.Users.Where(o => o.UserName == context.UserName && o.Password == context.Password).FirstOrDefault();//LINQ query checking the username
- //and password from db
- if (user != null)
- {
- //Store information againest the request
- identity.AddClaim(new Claim("UserName", context.UserName));
- identity.AddClaim(new Claim("LoggedOn", DateTime.Now.ToString()));
- context.Validated(identity);
- }
- else
- {
- context.SetError("Wrong Crendtials", "Provided username and password is incorrect");
- context.Rejected();
- }
- }
- else
- {
- context.SetError("Wrong Crendtials", "Provided username and password is incorrect");
- context.Rejected();
- }
- return;
- }
- }
- }
- }
Step 5
Delete the Global.asax class because we will not use this class in this project. We will create our own startup class so create a startup class and paste this code into that.
Startup.cs
- 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;
- using WebAPI_Oauth.Provider;
- namespace WebAPI_Oauth
- {
- public class Startup
- {
- public void ConfigureAuth(IAppBuilder app)
- {
- app.UseCors(CorsOptions.AllowAll);//this is very important line cross orgin source(CORS)it is used to enable cross-site HTTP requests
- //For security reasons, browsers restrict cross-origin HTTP requests
- var OAuthOptions = new OAuthAuthorizationServerOptions
- {
- AllowInsecureHttp = true,
- TokenEndpointPath = new PathString("/token"),
- AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),//token expiration time
- Provider = new OauthProvider()
- };
- app.UseOAuthBearerTokens(OAuthOptions);
- app.UseOAuthAuthorizationServer(OAuthOptions);
- app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
- HttpConfiguration config = new HttpConfiguration();
- WebApiConfig.Register(config);//register the request
- }
- public void Configuration(IAppBuilder app)
- {
- ConfigureAuth(app);
- GlobalConfiguration.Configure(WebApiConfig.Register);
- }
- }
- }
Step 6
Create WebAPI2 Controller and name it ProductController.

ProductController.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- using WebAPI_Oauth.Models;
- namespace WebAPI_Oauth.Controllers
- {
- [RoutePrefix("Api/Product")]//This is Route prefix filter which will be added in the URL for this specific controller
- [Authorize]//This filter redirects the request to the provider class first request will authenticate if authentication successful than it will come to here
- public class ProductController : ApiController
- {
- [HttpGet]
- [Route("GetProducts")]
- public List<Product> GetProducts()//This is th get method which get all the products from the db and return
- {
- List<Product> productList = new List<Product>();
- using (DataContext dataContext=new DataContext())
- {
- productList = dataContext.Products.ToList();
- }
- return productList;
- }
- [HttpGet]
- [Route("GetProductById/{Id}")]
- public Product GetProductById(string Id)//This is th get method which get one record on the basis of ID
- {
- Product product = new Product();
- using (DataContext dataContext = new DataContext())
- {
- product = dataContext.Products.Find(Convert.ToInt32(Id));
- }
- return (product);
- }
- [HttpPost]
- [Route("InsertProduct")]
- public IHttpActionResult Create(Product product)//This method will insert the product into db
- {
- using (DataContext dataContext = new DataContext())
- {
- if (!ModelState.IsValid)
- {
- return BadRequest(ModelState);
- }
- else
- {
- dataContext.Products.Add(product);
- dataContext.SaveChanges();
- return Ok(product);
- }
- }
- }
- [HttpPut]
- [Route("UpdateProduct")]
- public IHttpActionResult Update(Product product)//Update method will update the product
- {
- using (DataContext dataContext = new DataContext())
- {
- if (ModelState.IsValid)
- {
- dataContext.Entry(product).State = System.Data.Entity.EntityState.Modified;
- dataContext.SaveChanges();
- return Ok(product);
- }
- else
- {
- return BadRequest(ModelState);
- }
- }
- }
- [HttpDelete]
- [Route("DeleteProduct/{Id}")]
- public IHttpActionResult Delete(int Id)//this method will Delete the record
- {
- using (DataContext dataContext = new DataContext())
- {
- Product product = dataContext.Products.Find(Convert.ToInt32(Id));
- if (product == null) { return NotFound(); }
- else
- {
- dataContext.Products.Remove(product);
- dataContext.SaveChanges();
- return Ok(product);
- }
- }
- }
- }
- }
Step 10
Run this project and test this Web API using POSTMAN.

Step 11
Now, paste this token in authorization and call the GetProducts method.

Conclusion
In this article, we have successfully developed the Web API project using OAuth2.0 and also implemented the CRUD methods in ProductController. The front-end of this project is in Part 2 where we will consume this Web API and will perform the CRUD operations. If you face any problem or you have any query, please feel free to comment in the comment section below.
Don’t forget to like and share it.

Shishir GaikwadPosted Aug 18, 2021, 1:22 PM
Both codes from git and from the site are not working
Amit MohantyPosted Aug 27, 2019, 11:18 PM
Useful article