Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test ASP.NET Core Web API with cookie authentication using Postman?

I have an ASP.NET Core MVC Web Application (.NET Core 2.1) that implements Cookie Authentication as follows:

services.AddAuthentication(options => {
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie(options => {
    options.LoginPath = "/account/login";
    options.LogoutPath = "/account/logout";
});

The web application also includes a web API where client-side JavaScript makes Ajax calls back to the web server. The web API controllers are decorated with [Authorize]; requiring the user to login via the web application before the Ajax calls can access the web API methods.

I want to use Postman (Windows native application) to test the web API calls while running the web application on localhost. How do I copy the authentication cookies into Postman from the browser after logging in?

like image 612
Chris Keith Avatar asked Jan 27 '23 12:01

Chris Keith


1 Answers

To copy cookies from the browser to Postman, you'll need to use the Browser's Developer Tools and Postman's Manage Cookies feature.

  1. Run and log into your web application and open the Browser's Developer Tools.
  2. From Developer Tools, locate the list of cookies for localhost. Using Chrome (version 73) as an example, select the Application tab and expand the Storage > Cookies option.
  3. From the Cookies option, click on your localhost web application e.g. http://localhost:port. This will display the list of cookies.
  4. Having logged into your web application, a cookie named .AspNetCore.Cookies should be present. Copy the value i.e. it should be a long string of characters such as CfDJ8FNwIhImGGFJmGnb...
  5. From Postman, create a request to access your chosen web API method and locate the Cookies option for the request. Example from Postman (v7.0.6) below: Postman (v7.0.6) Cookies option screenshot

  6. From within Manage Cookies, add a new cookie. Example from Postman (v7.0.6) below:

    Postman (v7.0.6) Adding Cookie from Manage Cookies screenshot

  7. The placeholder value should be updated from:

    Cookie_1=value; path=/; domain=localhost;

    to

    .AspNetCore.Cookies=CfDJ8FNwIhImGGFJmGnb...shortened for brevity...; path=/; domain=localhost;

  8. Click send. The response should be the data or error returned from the web API method call and not the HTML of your login page. If it's the login page HTML, then the cookie or cookie value is most likely incorrect.

like image 60
Chris Keith Avatar answered Feb 01 '23 17:02

Chris Keith