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).
- Basic Authentication
- OAuth2.0
- JWT
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".
Step 2
Now, let's create an ASP.NET Project. For this, open Visual Studio and select New > Api_Project.
Select Web API Project with No Authentication.
Step 3
Now, create a folder named Authentication.
Add a new class in this folder. The class name is BasicAuthentication.
Now, add the following Authorization code to this class.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Security.Principal;
- using System.Threading;
- using System.Web;
- using System.Web.Http.Controllers;
- using System.Web.Http.Filters;
-
- namespace Api_Project.Authentication
- {
- public class BasicAuthentication : AuthorizationFilterAttribute
- {
- public override void OnAuthorization(HttpActionContext actionContext)
- {
- try
- {
- if (actionContext.Request.Headers.Authorization != null)
- {
-
- var authToken = actionContext.Request.Headers.Authorization.Parameter;
-
- var decoAuthToken = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(authToken));
-
- var UserNameAndPassword = decoAuthToken.Split(':');
-
- if (IsAuthorizedUser(UserNameAndPassword[0], UserNameAndPassword[1]))
- {
-
- Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(UserNameAndPassword[0]), null);
- }
- else
- {
- actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
- }
- }
- else
- {
- actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
- }
- }
- catch (Exception ex)
- {
- ex.Message.ToString();
- }
- }
- public static bool IsAuthorizedUser(string Username, string Password)
- {
-
-
- return Username == "shahbaz" && Password == "abc123";
- }
- }
- }
Step 4
Now, we need to connect our Web API to the database using Entity Framework. Just create a DataContext Model.
Add>New>DataContext.
Select EF Designer from the database.
Select the database name on the next screen.
Select the table and click "Finish".
Step 5
Create a Web API Controller now. For that, go to Add > New > Web API 2 Controller - Empty.
Add this code to the Controller.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- using Api_Project.Models;
-
- namespace Api_Project.Controllers
- {
- [RoutePrefix("Api/Product")]
- public class ProductController : ApiController
- {
- [Authentication.BasicAuthentication]
- [HttpGet]
- [Route("ProductDetails")]
- public List<Product_Table> GetProducts()
- {
- using (BasicDbEntities db=new BasicDbEntities())
- {
- return db.Product_Table.ToList();
- }
- }
- }
- }
ProductController.cs
Step 6
Now, we will test our Web API using POSTMAN. If you don't have POSTMAN, please download it.
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.
Wow
! 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.