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
Step 3
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
  1. using Microsoft.Owin.Security.OAuth;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Security.Claims;
  6. using System.Threading.Tasks;
  7. using System.Web;
  8. using WebAPI_Oauth.Models;
  9. namespace WebAPI_Oauth.Provider
  10. {
  11. public class OauthProvider : OAuthAuthorizationServerProvider
  12. {
  13. public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
  14. {
  15. //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
  16. //password the request will reject from here not proceded any further
  17. context.Validated();
  18. }
  19. public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
  20. {
  21. //If the request has valid and it contain username and password than this method will check correct crenstials and than generate a valid token
  22. var identity = new ClaimsIdentity(context.Options.AuthenticationType); //it will check the authenticate type
  23. using (var db = new DataContext())
  24. {
  25. if (db != null)
  26. {
  27. var user = db.Users.Where(o => o.UserName == context.UserName && o.Password == context.Password).FirstOrDefault();//LINQ query checking the username
  28. //and password from db
  29. if (user != null)
  30. {
  31. //Store information againest the request
  32. identity.AddClaim(new Claim("UserName", context.UserName));
  33. identity.AddClaim(new Claim("LoggedOn", DateTime.Now.ToString()));
  34. context.Validated(identity);
  35. }
  36. else
  37. {
  38. context.SetError("Wrong Crendtials", "Provided username and password is incorrect");
  39. context.Rejected();
  40. }
  41. }
  42. else
  43. {
  44. context.SetError("Wrong Crendtials", "Provided username and password is incorrect");
  45. context.Rejected();
  46. }
  47. return;
  48. }
  49. }
  50. }
  51. }
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
  1. using Microsoft.Owin;
  2. using Microsoft.Owin.Cors;
  3. using Microsoft.Owin.Security.OAuth;
  4. using Owin;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Web;
  9. using System.Web.Http;
  10. using WebAPI_Oauth.Provider;
  11. namespace WebAPI_Oauth
  12. {
  13. public class Startup
  14. {
  15. public void ConfigureAuth(IAppBuilder app)
  16. {
  17. app.UseCors(CorsOptions.AllowAll);//this is very important line cross orgin source(CORS)it is used to enable cross-site HTTP requests
  18. //For security reasons, browsers restrict cross-origin HTTP requests
  19. var OAuthOptions = new OAuthAuthorizationServerOptions
  20. {
  21. AllowInsecureHttp = true,
  22. TokenEndpointPath = new PathString("/token"),
  23. AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),//token expiration time
  24. Provider = new OauthProvider()
  25. };
  26. app.UseOAuthBearerTokens(OAuthOptions);
  27. app.UseOAuthAuthorizationServer(OAuthOptions);
  28. app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
  29. HttpConfiguration config = new HttpConfiguration();
  30. WebApiConfig.Register(config);//register the request
  31. }
  32. public void Configuration(IAppBuilder app)
  33. {
  34. ConfigureAuth(app);
  35. GlobalConfiguration.Configure(WebApiConfig.Register);
  36. }
  37. }
  38. }
Step 6
Create WebAPI2 Controller and name it ProductController.
ProductController.cs
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Http;
  6. using System.Web.Http;
  7. using WebAPI_Oauth.Models;
  8. namespace WebAPI_Oauth.Controllers
  9. {
  10. [RoutePrefix("Api/Product")]//This is Route prefix filter which will be added in the URL for this specific controller
  11. [Authorize]//This filter redirects the request to the provider class first request will authenticate if authentication successful than it will come to here
  12. public class ProductController : ApiController
  13. {
  14. [HttpGet]
  15. [Route("GetProducts")]
  16. public List<Product> GetProducts()//This is th get method which get all the products from the db and return
  17. {
  18. List<Product> productList = new List<Product>();
  19. using (DataContext dataContext=new DataContext())
  20. {
  21. productList = dataContext.Products.ToList();
  22. }
  23. return productList;
  24. }
  25. [HttpGet]
  26. [Route("GetProductById/{Id}")]
  27. public Product GetProductById(string Id)//This is th get method which get one record on the basis of ID
  28. {
  29. Product product = new Product();
  30. using (DataContext dataContext = new DataContext())
  31. {
  32. product = dataContext.Products.Find(Convert.ToInt32(Id));
  33. }
  34. return (product);
  35. }
  36. [HttpPost]
  37. [Route("InsertProduct")]
  38. public IHttpActionResult Create(Product product)//This method will insert the product into db
  39. {
  40. using (DataContext dataContext = new DataContext())
  41. {
  42. if (!ModelState.IsValid)
  43. {
  44. return BadRequest(ModelState);
  45. }
  46. else
  47. {
  48. dataContext.Products.Add(product);
  49. dataContext.SaveChanges();
  50. return Ok(product);
  51. }
  52. }
  53. }
  54. [HttpPut]
  55. [Route("UpdateProduct")]
  56. public IHttpActionResult Update(Product product)//Update method will update the product
  57. {
  58. using (DataContext dataContext = new DataContext())
  59. {
  60. if (ModelState.IsValid)
  61. {
  62. dataContext.Entry(product).State = System.Data.Entity.EntityState.Modified;
  63. dataContext.SaveChanges();
  64. return Ok(product);
  65. }
  66. else
  67. {
  68. return BadRequest(ModelState);
  69. }
  70. }
  71. }
  72. [HttpDelete]
  73. [Route("DeleteProduct/{Id}")]
  74. public IHttpActionResult Delete(int Id)//this method will Delete the record
  75. {
  76. using (DataContext dataContext = new DataContext())
  77. {
  78. Product product = dataContext.Products.Find(Convert.ToInt32(Id));
  79. if (product == null) { return NotFound(); }
  80. else
  81. {
  82. dataContext.Products.Remove(product);
  83. dataContext.SaveChanges();
  84. return Ok(product);
  85. }
  86. }
  87. }
  88. }
  89. }
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.