In today's article, we will learn how a basic Web API authentication works and which methods are used to access the Web API.
Later on, in the next article, we will demonstrate the OAuth2.0 and JSON Web Token (JWT).
  1. Basic Authentication
  2. OAuth2.0
  3. JWT
Source Code is available at Api_Project.
First, we will use a basic method/technique (Basic Web API authentication). Then, we will learn how a Web API credential passes from POSTMAN application to Web API and how a Web API first receives the credentials, authorizes or unauthorizes, and sends a response back. As we know, in the basic Web API authentication method, we use the credential as a username and password.
Lets's start step by step.
Step 1
First, we will create a simple database containing a single table.
Step 2
Then, we will create a simple ASP.NET MVC Web API project.
Step 3
Create a class for authentication (BasicAuthentication.cs).
Step 4
Create an Entity Framework DataModel and connect to the database.
Step 5
After that, we need to go to our controller and create a Get method to fetch the data from the database and return back.
Step 6
Finally, we will test our Web API using POSTMAN.

Step 1 - Create a simple Database

Lets' create a database with the name "BasicDb" and a single table with the name "Product".
ASP.NET Web API Authorization By Basic Auth/Oauth2.0/JWT
Step 2
Now, let's create an ASP.NET Project. For this, open Visual Studio and select New > Api_Project.
ASP.NET Web API Authorization By Basic Auth/Oauth2.0/JWT
Select Web API Project with No Authentication.
ASP.NET Web API Authorization By Basic Auth/Oauth2.0/JWT
Step 3
Now, create a folder named Authentication.
ASP.NET Web API Authorization By Basic Auth/Oauth2.0/JWT
Add a new class in this folder. The class name is BasicAuthentication.
ASP.NET Web API Authorization By Basic Auth/Oauth2.0/JWT
Now, add the following Authorization code to this class.
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Http;
  6. using System.Security.Principal;
  7. using System.Threading;
  8. using System.Web;
  9. using System.Web.Http.Controllers;
  10. using System.Web.Http.Filters;
  11. namespace Api_Project.Authentication
  12. {
  13. public class BasicAuthentication : AuthorizationFilterAttribute
  14. {
  15. public override void OnAuthorization(HttpActionContext actionContext)
  16. {
  17. try
  18. {
  19. if (actionContext.Request.Headers.Authorization != null)
  20. {
  21. //Taking the parameter from the header
  22. var authToken = actionContext.Request.Headers.Authorization.Parameter;
  23. //decode the parameter
  24. var decoAuthToken = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(authToken));
  25. //split by colon : and store in variable
  26. var UserNameAndPassword = decoAuthToken.Split(':');
  27. //Passing to a function for authorization
  28. if (IsAuthorizedUser(UserNameAndPassword[0], UserNameAndPassword[1]))
  29. {
  30. // setting current principle
  31. Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(UserNameAndPassword[0]), null);
  32. }
  33. else
  34. {
  35. actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
  36. }
  37. }
  38. else
  39. {
  40. actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
  41. }
  42. }
  43. catch (Exception ex)
  44. {
  45. ex.Message.ToString();
  46. }
  47. }
  48. public static bool IsAuthorizedUser(string Username, string Password)
  49. {
  50. // In this method we can handle our database logic here...
  51. //Here we have given the hard-coded values
  52. return Username == "shahbaz" && Password == "abc123";
  53. }
  54. }
  55. }
Step 4
Now, we need to connect our Web API to the database using Entity Framework. Just create a DataContext Model.
Add>New>DataContext.
ASP.NET Web API Authorization By Basic Auth/Oauth2.0/JWT
Select EF Designer from the database.
ASP.NET Web API Authorization By Basic Auth/Oauth2.0/JWT
Select the database name on the next screen.
ASP.NET Web API Authorization By Basic Auth/Oauth2.0/JWT
Select the table and click "Finish".
ASP.NET Web API Authorization By Basic Auth/Oauth2.0/JWT
Step 5
Create a Web API Controller now. For that, go to Add > New > Web API 2 Controller - Empty.
ASP.NET Web API Authorization By Basic Auth/Oauth2.0/JWT
Add this code to the Controller.
  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 Api_Project.Models;
  8. namespace Api_Project.Controllers
  9. {
  10. [RoutePrefix("Api/Product")]
  11. public class ProductController : ApiController
  12. {
  13. [Authentication.BasicAuthentication]
  14. [HttpGet]
  15. [Route("ProductDetails")]
  16. public List<Product_Table> GetProducts()
  17. {
  18. using (BasicDbEntities db=new BasicDbEntities())
  19. {
  20. return db.Product_Table.ToList();
  21. }
  22. }
  23. }
  24. }
ProductController.cs
ASP.NET Web API Authorization By Basic Auth/Oauth2.0/JWT
Step 6
Now, we will test our Web API using POSTMAN. If you don't have POSTMAN, please download it.
ASP.NET Web API Authorization By Basic Auth/Oauth2.0/JWT
Now, paste the URL and press Enter. Look at the highlighted message (401 Unauthorized) because we didn't pass the credentials. Let's pass the credential Username and password. Given below is the output.
ASP.NET Web API Authorization By Basic Auth/Oauth2.0/JWT
WowASP.NET Web API Authorization By Basic Auth/Oauth2.0/JWT! We did it successfully. We have returned the data from the database and successfully authorized the credentials.
If you find anything wrong in this article or you have a query, please write in the comment section below.
Part 2 and Part 3 will be coming soon.ASP.NET Web API Authorization By Basic Auth/Oauth2.0/JWT