Open In App

How to Handle Authentication with Postman API Testing?

Last Updated : 15 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Authentication is very important for securing access to resources and data. When testing APIs, handling authentication correctly is important to ensure that your tests can interact with secured endpoints effectively. Postman, a popular API testing tool, provides robust features for handling various authentication methods. This article will guide you through the process of handling authentication in Postman API testing, covering different authentication types and best practices.

All-Authorisations
All Authorization ways in Postman

Postman supports several authentication methods

1. No Auth

If the request doesn't require any authentication then we can use such Authentication technique. It has been used for the requests for Login or Creating a Account. In such APIs we generally don't require and token for validating the user.

2. Basic Auth

In this we are passing Username and password as a header with each and every request. On the server side this headers would get verified and then only the request would get served.

Basic-AUth
Basic Auth

We can also see the headers in which the username and password is converted to Base64 encoded String with Basic in the prefix for security

Basic-Auth-Headers
Authorisation As Headers

3. Bearer Token

Bearer tokens enable requests to authenticate using an access key, such as a JSON Web Token (JWT). The token is a text string, included in the request header. After Login API, generally a JWT token is returned as a response and that is used in the further requests Using the Bearer Token. This is the widely used technique.

Bearer-Token
Bearer Token

4. JWT Bearer

JWT Bearer is the extended form of Bearer Token. In this we will specify the token, Payload and Security in Postman itself. It means that in above method we were passing the only token which was returned from the Login API but here we will create one and then Postman will create the bearer Token and then that token would be passed as a Headers.

JWT-Token
JWT Token

5. OAuth 1.0

When we have to call the third party API then generally we use OAuth authentication. Because it provides us the flow to call a third party api using a secret token. Firstly Consumer or client will request a access token using a key and secret. Once the access token is received now this access token will be used to get the resources till the access token is not expired.

OAuth-10-
OAuth 1.0

6. OAuth 2.0

This is the extension of OAuth 1.0 in this the lifetime of access token is reduces and one new token which is a refresh token is sent with it. The lifetime of Refresh token is still long and whenever the access token is expired new token will be generated using this refresh token. This provides more security because if the access token is leaked then also it would be used for short time only.

OAuth-20-
OAuth 2.0

Example: In this example we are implementing a basic authentication to access the API data

C#
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Text.Json.Nodes;

namespace GeeksForGeeks_API_Project.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", 
             "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [Authorize]
        [HttpGet(Name = "GetWeatherForecast"), Authorize]
        public IEnumerable<WeatherForecast> Get()
        {
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }

        [HttpPost]
        public IActionResult SignIn([FromBody] SignInModel signInModel)
        {
            if (signInModel.Email != "[email protected]")
                return NotFound(new JsonObject() { { "Error", "User Not Found" } });

            bool result = signInModel.Email == "[email protected]" 
                && signInModel.Password == "test@1234";

            if (result)
            {
                var authClaims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, signInModel.Email),
                    new Claim(ClaimTypes.Email, signInModel.Email),
                    new Claim(System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames.Jti , 
                    Guid.NewGuid().ToString())
                };

                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("+)
                3@5!7#9$0%2^4&+)3@5!7#9$0%2^4&6*8(06*8(0+)3@5!7#9$0%2^4&6*8(07#9$0%2^4&"));
                var tokenDescriptor = new SecurityTokenDescriptor()
                {

                    Subject = new ClaimsIdentity(authClaims),
                    Expires = DateTime.UtcNow.AddHours(24 - DateTime.UtcNow.Hour),
                    SigningCredentials = new SigningCredentials(key,
                     SecurityAlgorithms.HmacSha512Signature)
                };

                var tokenHandler = new JwtSecurityTokenHandler();
                var token = tokenHandler.CreateToken(tokenDescriptor);

                return Ok(new JsonObject { { "Success", "User Logged In" }, 
                { "User", tokenHandler.WriteToken(token).ToString() }, 
                { "Valid", token.ValidTo } });

            }
            return BadRequest(new JsonObject() { { "Error", "Wrong Password" } });
        }
    }
}

Output


Conclusion

As Postman comes with so many options for authentication but this are some basic ones which we can use in our applications. Other methods like AWS Signature or Hawk Authentication are the methods in which we require the tokens from the respected entitles. API key is the method in which we give key value pairs which can be passed as Headers or Query Parameters. So, this is basic authentication but with postman we can do so many things. We can create Postman Collections or we can create Mock Server in Postman.


Next Article

Similar Reads