How to Handle Authentication with Postman API Testing?
Last Updated : 15 Jul, 2024
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 Authorization ways in PostmanPostman 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 AuthWe can also see the headers in which the username and password is converted to Base64 encoded String with Basic in the prefix for security
Authorisation As Headers3. 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 Token4. 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 Token5. 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 1.06. 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 2.0Example: 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.
Similar Reads
Automating API Testing with Postman
Testing the functionality, dependability, and performance of an API is known as API testing. API testing can be done automatically or manually. The technique of automating the execution of API tests with tools is known as automated API testing. This can save time and effort, as well as ensure that A
5 min read
How to add Bearer Token authentication in Postman ?
Postman is a crucial platform for developers, aiding in API testing, creation, and modification. APIs support various website features, such as user registration and login. For secure actions like changing passwords, Bearer Token Authentication is used. Upon login, the server issues a token, acting
3 min read
Navigating API Testing with Postman
API(Application Programming Interface) testing plays a pivotal role in the software development lifecycle, ensuring the seamless functionality of APIs and safeguarding against potential issues. Postman, a comprehensive API development and testing tool, offers a range of features to streamline and en
6 min read
How to do Basic Load Testing with Postman?
Load testing is an important way of ensuring the performance and reliability of web applications under various levels of stress. Postman, a popular API testing tool, offers capabilities for conducting basic load testing to simulate multiple users accessing an API concurrently. In this article, we'll
2 min read
How to Use API Keys authentication in Postman
Postman is an API(application programming interface) development tool that helps to build, test and modify APIs. In this tutorial, we will see how to use API Keys authentication in Postman. The API key is a unique identifier that authenticates requests and if several users are there, their username
2 min read
How to set authorization headers in Postman?
Web application security is vital, and JSON Web Tokens (JWT) play a key role in authentication and route protection. In this article we will learn how to create a secure backend with Node and Express using JWT, and then we will demonstrate how to set authorization headers in Postman for effective AP
3 min read
Elasticsearch API Authentication: How to Set Up with Examples
Elasticsearch is a powerful distributed search and analytics engine widely used for logging, monitoring, and data analysis. To protect your data and ensure secure access, setting up API authentication is essential. This article will guide you through the process of configuring Elasticsearch API auth
5 min read
How to use postman for testing express application
Testing an Express app is very important to ensure its capability and reliability in different use cases. There are many options available like Thunder client, PAW, etc but we will use Postman here for the testing of the Express application. It provides a great user interface and numerous tools whic
3 min read
How to test API Endpoints with Postman and Express ?
Postman, a popular API development and testing tool allowing developers to interact with APIs. In this guide, we'll explore the basics of testing API endpoints using Postman and Express, providing clear steps and examples. Prerequisites:Basics of Express JS and Node JS.Postman should be installed.St
2 min read
How to generate API documentation using Postman?
Postman is a popular API testing tool that is used to simplify the process of developing and testing APIs (Application Programming Interface). API acts as a bridge between two software applications which enables them to communicate and share data. In this article, you will learn how to generate API
2 min read