简体   繁体   English

使用发布请求获取身份验证令牌

[英]Get auth token using post request

I am trying to get request auth token by making a post web request to a url. 我试图通过向网址发布网络请求来获取请求身份验证令牌。 The api expects username/password as credentials in the form-data payload. api期望用户名/密码作为form-data有效负载中的凭证。

When I click the sign-in option on the browser, the network logs show a GET request with HTML as response, followed by a POST request which returns form-data with username/password and request token in payload. 当我单击浏览器上的登录选项时,网络日志显示带有HTML作为响应的GET请求,然后是POST请求,该请求返回带有用户名/密码的表单数据和有效负载中的请求令牌。

浏览器的网络日志..

Trying to mock the flow using webrequest , I am doing a simple post request, as the following: 尝试使用webrequest模拟流程,我正在做一个简单的post请求,如下所示:

public string HttpPost(string url, string post, string refer = "")
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            // request.CookieContainer = cJar;
            request.UserAgent = UserAgent;
            request.KeepAlive = false;
            request.Method = "POST";
            request.Referer = refer;

            byte[] postBytes = Encoding.ASCII.GetBytes(post);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postBytes.Length;

            Stream requestStream = request.GetRequestStream();
            requestStream.Write(postBytes, 0, postBytes.Length);
            requestStream.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream());

            return sr.ReadToEnd();
        }

However, this request only returns the text/HTML markup of the page as the first part of the request of the browser does. 但是,此请求仅返回页面的文本/ HTML标记,作为浏览器请求的第一部分。 How do I get it to run the subsequent POST to fetch the token from the endpoint? 如何让它运行后续POST以从端点获取令牌?

EDIT 1: 编辑1:

Here is the first GET Request: 这是第一个GET请求:

在此输入图像描述

The token is a CSRF token, what you need to do is find the login form in the html response that you've received with your initial get request, and also to ensure you are storing the cookies set in this response. 令牌是CSRF令牌,您需要做的是在初始获取请求中收到的html响应中找到登录表单,并确保您存储在此响应中设置的cookie。

You will then need to search within the html response for the hidden input parameter named 'token' next to the username and pw input fields and use the value of that element to compose your post request. 然后,您需要在html响应中搜索用户名和pw输入字段旁边名为“token”的隐藏输入参数,并使用该元素的值来组成您的发布请求。

Doing this programmatically is possible with some regex or the htmlagilitypack to extract that token 使用某些正则表达式或htmlagilitypack可以以编程方式执行此操作以提取该令牌

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM