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.
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
- 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)
- {
-
-
- context.Validated();
- }
- public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
- {
-
- var identity = new ClaimsIdentity(context.Options.AuthenticationType);
-
- using (var db = new DataContext())
- {
- if (db != null)
- {
- var user = db.Users.Where(o => o.UserName == context.UserName && o.Password == context.Password).FirstOrDefault();
-
- if (user != null)
- {
-
- 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);
-
- var OAuthOptions = new OAuthAuthorizationServerOptions
- {
- AllowInsecureHttp = true,
- TokenEndpointPath = new PathString("/token"),
- AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),
- Provider = new OauthProvider()
- };
-
- app.UseOAuthBearerTokens(OAuthOptions);
- app.UseOAuthAuthorizationServer(OAuthOptions);
- app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
-
- HttpConfiguration config = new HttpConfiguration();
- WebApiConfig.Register(config);
- }
-
- 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")]
- [Authorize]
- public class ProductController : ApiController
- {
- [HttpGet]
- [Route("GetProducts")]
- public List<Product> GetProducts()
- {
- 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)
- {
- 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)
- {
- 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)
- {
- 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)
- {
- 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.