Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call API with AntiForgeryToken using Postman in IdentityServer ASP.NET Core

I'm trying to test my API with Identity Server Asp.net Core using Postman.

This is the way that I'm trying to do:

  1. First request HttpGet to https://localhost:5000/Account/Login and in response body I received: <input name="__RequestVerificationToken" type="hidden" value="CfDJ8MoS9upoM4dNp8Kx-AdvA-uYr13_PAkuMZpzYMV8UmxZq5GdLTvN-Ht5NpTLmPtlhL5d5z2Hu2vUJoJGhk1AMlARDcOwqgq7Cef1dfQL_vl4tIFM4kx9RZPz8DHU26-U9qLnKAIstZgR42-1FuGNh24" />

And in Cookie (not sure for what it is though): enter image description here

  1. Then HttpPost to https://localhost:5000/Account/Login with RequestVerificationToken with token received from body HttpGet request. enter image description here

And always error 400 as you can see at screen shot above.

In Visual studio I can see that some request was catched but clearly was incorrect. enter image description here

If I'll remove attribute [ValidateAntiForgeryToken] then of course everything works fine but obviously because that validation is disabled.

like image 329
DiPix Avatar asked Jun 02 '18 13:06

DiPix


People also ask

What is AntiForgeryToken in asp net core?

In ASP.NET Core, @Html. AntiForgeryToken() is applied for preventing cross-site request forgery (XSRF/CSRF) attacks.

What is the use of HTML AntiForgeryToken ()?

AntiForgeryToken()Generates a hidden form field (anti-forgery token) that is validated when the form is submitted.

What is AntiForgeryToken in Web API?

Adding an AntiForgeryToken generates a Cryptographically valid hash at the server end which is split and a part is added as a hidden field, whereas the rest goes into a cookie. When data is posted, the Cookie and the Hidden Field are both sent back and if they are missing or they don't match, the POST is rejected.


1 Answers

You'd need to do followings to send such a request:

1.) Enter __RequestVerificationToken key value (don't forget double underscores) into x-www-form-urlencoded

2.) You need to add .AspNetCore.Antiforgery cookie to the Cookies section in Postman.

For example like this .AspNetCore.Antiforgery.1XHiLFgQI2w=your cookie value; Path=/; Domain=localhost;Expires=Session;

You can find .AspNetCore.Antiforgery cookie in Application section in Google Developer Tools

.AspNetCore.Antiforgery cookie in Google Developer Tools picture

Add cookie in Postman picture

like image 120
Burhan Savci Avatar answered Oct 25 '22 16:10

Burhan Savci