Skip to main content
  1. About
  2. For Teams
Asked
Modified 17 days ago
Viewed 58 times
0

I am using Ncat to send raw HTTP requests to the backend JS server. I will add here the backend and frontend files. We write ourselves, which is the goal of the task.

I have installed Ncat and I send the HTTP file through this command:

Get-Content -Path request.txt -Raw | ncat -q 1 localhost 8000

And this is inside the request.txt:

GET /pedidos HTTP/1.1
Host: localhost:8000
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InJvZHJpZ29nYWx2YW9ic0BnbWFpbC5jb20iLCJzZW5oYSI6IjEyMyIsImlhdCI6MTc1ODg4Njc5MywiZXhwIjoxNzU4OTI5OTkzfQ.pNRNhSV58wdKLtO1rdpBPZrTqxsexA2XTmrUMbHwKxg

The request I am making is a simple GET. But for this specific PATH I need an access token, which I obtained before running the same command with login.txt:

POST /public/login HTTP/1.1
Host: localhost:8000
Content-Type: application/json
Content-Length: 46

{"email": "[email protected]", "senha": "123"}

With that said: The POST works perfectly. I can send it and I receive a response back. The GET method doesn't work well. In my backend logs I see the following:

Backend Log

I thought it could be some timeout problem I added some in the server but it did not work.

I used Postman to make this authenticated request and it worked just fine. The page was returned successfully.

I looked also into Wireshark but I couldn't interpretate it. those are the logs: With Ncat: logs with Ncat

With Postman: logs with Postman

1 Answer 1

0

Using those five simple version of Power Script first

  1. Register – Creates the user by POSTing JSON (email, senha) to /public/registrar. You usually do this once; if the email exists, the server may return an “already used” error.

  2. Log in – Authenticates with the same credentials via /public/login. The server responds with JSON containing an access_token (a JWT).

  3. Extract token – Pulls the access_token field from the login response into $ACCESS_TOKEN.

  4. Verify/debug – Prints the token so you can confirm you actually received it (handy for troubleshooting).

  5. Call a protected route – Sends a GET to /categorias with header Authorization: Bearer (plus JSON Content-Type). The server validates the token and returns the protected data.

#1
Invoke-RestMethod -Method POST "http://localhost:8000/public/registrar" `
  -ContentType "application/json" `
  -Body (@{ email = "[email protected]"; senha = "123" } | ConvertTo-Json -Compress)


#2
$response = Invoke-RestMethod -Method POST "http://localhost:8000/public/login" `
  -Headers @{ "Content-Type" = "application/json" } `
  -Body '{"email":"[email protected]","senha":"123"}'

#3
$ACCESS_TOKEN = $response.access_token

#4
Write-Output "Token: $ACCESS_TOKEN"

#5
Invoke-RestMethod -Method GET "http://localhost:8000/categorias" `
  -Headers @{ 
    "Content-Type" = "application/json"; 
    "Authorization" = "Bearer $ACCESS_TOKEN" 
  }

Then Ncap version of script Save as ncat-call.ps1

Registry call already upper simple #1 step

Set-StrictMode -Version Latest

$ErrorActionPreference = 'Stop'

# --- 1) Login (hardcoded) ---
$loginUrl = 'http://localhost:8000/public/login'
$email    = '[email protected]'
$senha    = '123'

try {
  $resp = Invoke-RestMethod -Method POST $loginUrl `
    -Headers @{ 'Content-Type' = 'application/json' } `
    -Body (@{ email = $email; senha = $senha } | ConvertTo-Json -Compress)
  $ACCESS_TOKEN = $resp.access_token
  if (-not $ACCESS_TOKEN) { throw "Login succeeded but no access_token in response." }
  Write-Host "Token: $ACCESS_TOKEN" -ForegroundColor Green
} catch {
  Write-Host "Login failed:" -ForegroundColor Red
  throw
}

# --- 2) Build raw HTTP request (CRLF line endings are important) ---
$request =
"GET /categorias HTTP/1.1`r`n" +
"Host: localhost:8000`r`n" +
"Accept: application/json`r`n" +
"Authorization: Bearer $ACCESS_TOKEN`r`n" +
"Connection: close`r`n" +
"`r`n"

# --- 3) Send via raw TCP and read full response ---
$client = [System.Net.Sockets.TcpClient]::new('127.0.0.1', 8000)
$stream = $client.GetStream()
$stream.ReadTimeout = 10000

# Write request
$bytes = [Text.Encoding]::ASCII.GetBytes($request)
$stream.Write($bytes, 0, $bytes.Length)
$stream.Flush()

# Read until server closes the connection
$buffer = New-Object byte[] 8192
$ms = New-Object System.IO.MemoryStream
while ($true) {
  $read = $stream.Read($buffer, 0, $buffer.Length)
  if ($read -le 0) { break }
  $ms.Write($buffer, 0, $read)
  if (-not $stream.DataAvailable) { Start-Sleep -Milliseconds 25 }
}

$stream.Close(); $client.Close()
$raw = [Text.Encoding]::UTF8.GetString($ms.ToArray())

# --- 4) Extract JSON payload (don’t depend on headers) ---
$body = $raw
$idx  = $raw.IndexOf("`r`n`r`n"); if ($idx -ge 0) { $body = $raw.Substring($idx + 4) }
if ($idx -lt 0) { $lfIdx = $raw.IndexOf("`n`n"); if ($lfIdx -ge 0) { $body = $raw.Substring($lfIdx + 2) } }

# Find the first JSON array/object in body
$m = [regex]::Match($body, '(\[[\s\S]*\]|\{[\s\S]*\})')
if (-not $m.Success) {
  Write-Host "No JSON found in reply. Raw response below:" -ForegroundColor Red
  $raw
  exit 1
}

# --- 5) Parse & pretty-print ---
try {
  $data = $m.Value | ConvertFrom-Json
  if ($data -is [System.Collections.IEnumerable] -and -not ($data -is [string])) {
    $data | Format-Table -AutoSize
  } else {
    $data | ConvertTo-Json -Depth 50
  }
} catch {
  Write-Host "JSON parse failed; raw reply below:" -ForegroundColor Red
  $raw
  exit 1
}

Demo

Will call "http://localhost:8000/categorias" with access token

Running backend API server from CMD after npm install

npm run start-auth

enter image description here

Call 5 steps from Power Shell without Ncap

enter image description here

Call ncap-call.ps from Power Shell with Ncap

enter image description here

Backend from CMD enter image description here

Summary

Builds raw HTTP requests (login + /categorias) with proper headers and Content-Length. Sends them over ncat -C (CRLF), waiting for server close to capture the full response. Extracts the first JSON block from the raw reply and parses it to objects. Uses the login’s access_token to authorize /categorias and prints the results neatly.

Sign up to request clarification or add additional context in comments.

2 Comments

Hello! This is a very descriptive answer, and it's also very didactic. I really appreciate it! It worked perfectly for me. Although I don't understand where you used Ncat. Sorry, I am a bit lost with the commands and applications, and what exactly they are. For the login, and then you did a raw TCP connection to send and read. What is the problem with my approach? Why just a simple Ncat command with my raw HTTP file does not work? Like this one "Get-Content -Path request.txt -Raw | ncat -q 1 localhost 8000" What does using ncat actually mean? Thank you!!
On Windows, using Ncat with a request.txt file often doesn’t work reliably with Node’s HTTP parser, and there’s no guaranteed fix that always works. Alternatively using Invoke-RestMethod , second way or curl curl.exe -s "localhost:8000/categorias" -H "Authorization: Bearer $ACCESS_TOKEN"

Your Answer

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.