     [Blog](https://scrapfly.io/blog)   /  [api](https://scrapfly.io/blog/tag/api)   /  [cURL Authentication: Authorization Headers, Basic Auth and Bearer Tokens](https://scrapfly.io/blog/posts/curl-authentication)   

# cURL Authentication: Authorization Headers, Basic Auth and Bearer Tokens

 by [Mayada Shaaban](https://scrapfly.io/blog/author/mayada-shaaban-90143e67) Nov 24, 2026 21 min read [\#api](https://scrapfly.io/blog/tag/api) [\#curl](https://scrapfly.io/blog/tag/curl) [\#http](https://scrapfly.io/blog/tag/http) 

 [  ](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fscrapfly.io%2Fblog%2Fposts%2Fcurl-authentication "Share on LinkedIn") [  ](https://x.com/intent/tweet?url=https%3A%2F%2Fscrapfly.io%2Fblog%2Fposts%2Fcurl-authentication&text=cURL%20Authentication%3A%20Authorization%20Headers%2C%20Basic%20Auth%20and%20Bearer%20Tokens "Share on X") [  ](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fscrapfly.io%2Fblog%2Fposts%2Fcurl-authentication "Share on Facebook")    

 

 

Summarize this article with

 [  ](https://chat.openai.com/?q=Summarize%20this%20article%20and%20explain%20how%20Scrapfly%20helps%20me%20scrape%20any%20website%20at%20scale%20and%20bypass%20anti-bot%20systems%20for%20my%20use%20case%3A%20https%3A%2F%2Fscrapfly.io%2Fblog%2Fposts%2Fcurl-authentication) [  ](https://claude.ai/new?q=Summarize%20this%20article%20and%20explain%20how%20Scrapfly%20helps%20me%20scrape%20any%20website%20at%20scale%20and%20bypass%20anti-bot%20systems%20for%20my%20use%20case%3A%20https%3A%2F%2Fscrapfly.io%2Fblog%2Fposts%2Fcurl-authentication) [  ](https://x.com/i/grok?text=Summarize%20this%20article%20and%20explain%20how%20Scrapfly%20helps%20me%20scrape%20any%20website%20at%20scale%20and%20bypass%20anti-bot%20systems%20for%20my%20use%20case%3A%20https%3A%2F%2Fscrapfly.io%2Fblog%2Fposts%2Fcurl-authentication) [  ](https://www.perplexity.ai/search/new?q=Summarize%20this%20article%20and%20explain%20how%20Scrapfly%20helps%20me%20scrape%20any%20website%20at%20scale%20and%20bypass%20anti-bot%20systems%20for%20my%20use%20case%3A%20https%3A%2F%2Fscrapfly.io%2Fblog%2Fposts%2Fcurl-authentication) [  ](https://www.google.com/search?udm=50&aep=11&q=Summarize%20this%20article%20and%20explain%20how%20Scrapfly%20helps%20me%20scrape%20any%20website%20at%20scale%20and%20bypass%20anti-bot%20systems%20for%20my%20use%20case%3A%20https%3A%2F%2Fscrapfly.io%2Fblog%2Fposts%2Fcurl-authentication) 



         

One of the biggest challenges in cURL authentication is the 401 error which can be caused by a lot of different reasons. However, we can reduce most of these reasons to a single fact - the header cURL sends is different compared to the one the server expects (like `dXNlcjpwYXNzd2QK` from `echo 'user:passwd' | base64` instead of `dXNlcjpwYXNzd2Q=`).

The Authorization header carries the client's credentials: a username and password, a Bearer token or an API key.

Here we'll take a look at the Authorization header in cURL. How can we send our credentials without breaking them on the way to the server?

We'll take a look at common authentication schemes and what they mean, what are some challenges and best practices when it comes to quoting, shell history and redirects.



## Key Takeaways

- Use `-u user:password` for Basic auth and `-H "Authorization: Bearer $TOKEN"` for Bearer tokens - in double quotes, as single quotes send `$TOKEN` as plain text.
- Build Basic headers by hand with `printf` and not `echo`. Usual culprit here is the newline `echo` adds, which ends up inside the encoded password.
- Keep secrets off the command line through the password prompt, `.netrc`, header files or the `--variable` option (curl 8.3.0+).
- Avoid `--location-trusted` unless the redirect target is trusted. By default curl drops the `Authorization` header when redirected to another host, scheme or port.
- For web scraping, the [Scrapfly Web Scraping API](https://scrapfly.io/products/web-scraping-api) can forward our `Authorization` header to the scraped page through `headers[Authorization]` on plain requests.

**Get web scraping tips in your inbox**Trusted by 100K+ developers and 30K+ enterprises. Unsubscribe anytime.







## How Do You Send an Authorization Header With cURL?

Authorization is an identity header that tells the server who's making the request. By using the `-H` option we can specify it ourselves as `-H "Authorization: <scheme> <credentials>"`, or curl can generate it for us with `-u user:password` for Basic auth and `--oauth2-bearer <token>` for Bearer tokens.

| Scheme | curl option | Header curl sends | Try it on |
|---|---|---|---|
| Basic | `-u user:passwd` | `Authorization: Basic dXNlcjpwYXNzd2Q=` | httpbin.dev/basic-auth/user/passwd |
| Bearer | `-H "Authorization: Bearer TOKEN"` or `--oauth2-bearer TOKEN` | `Authorization: Bearer TOKEN` | httpbin.dev/bearer |
| Digest | `--digest -u user:passwd` | computed per challenge | httpbin.dev/digest-auth/auth/user/passwd |
| API key | `-H "X-API-Key: KEY"` or a query parameter | depends on the API | httpbin.dev/headers |

If we run any of these with `-v`, we can see the exact `> Authorization:` line curl is sending. In this example we're using httpbin.dev testing endpoint for Bearer tokens, which returns the token we sent as response body:

shell

```shell
$ curl https://httpbin.dev/bearer -H "Authorization: Bearer my-token-123"
{
  "authenticated": true,
  "token": "my-token-123"
}
```



httpbin.dev found our token in the header and sent it straight back.

[How to Use cURL For Web ScrapingIn this article, we'll go over a step-by-step guide on sending and configuring HTTP requests with cURL. We'll also explore advanced usages of cURL for web scraping, such as scraping dynamic pages and avoiding getting blocked.](https://scrapfly.io/blog/posts/how-to-use-curl-for-web-scraping)



## How Does Basic Authentication Work in cURL?

Basic authentication is `curl -u user:password URL`. Basic auth is used to send a username and password with every request - curl encodes `user:password` with base64 and sends it as `Authorization: Basic ...`, which anyone can decode back, so it's only safe over HTTPS.

### How Do You Use -u or --user?

httpbin.dev has a Basic auth endpoint that expects the username `user` and the password `passwd`. Let's call it once without credentials and once with `-u`:

shell

```shell
$ curl -s -o /dev/null -w '%{http_code}\n' https://httpbin.dev/basic-auth/user/passwd
401
$ curl -u user:passwd https://httpbin.dev/basic-auth/user/passwd
{
  "authorized": true,
  "user": "user"
}
```



The first request gets a 401 with `www-authenticate: Basic realm="Fake Realm"` in its headers, and the second one gets in!

If we pass only the username (`-u user`), curl asks for the password, so it never lands in the shell history:

shell

```shell
$ curl -u user https://httpbin.dev/basic-auth/user/passwd
Enter host password for user 'user':
{
  "authorized": true,
  "user": "user"
}
```



curl splits the value on the first colon. Meaning, the username can't contain a colon but the password can - `-u 'user:pa:ss'` logged in fine against `/basic-auth/user/pa:ss` (no `--basic` needed, as Basic is curl's default method).

### How Do You Build the Basic Authorization Header Yourself?

We can build the same header with `printf` and `base64` too (handy for tools that only accept raw headers), however the obvious `echo` version gives a different result:

shell

```shell
$ printf 'user:passwd' | base64
dXNlcjpwYXNzd2Q=
$ echo 'user:passwd' | base64
dXNlcjpwYXNzd2QK
$ curl -s -o /dev/null -w '%{http_code}\n' -H "Authorization: Basic dXNlcjpwYXNzd2QK" https://httpbin.dev/basic-auth/user/passwd
401
```



Here, `printf` gives base64 the 11 characters of `user:passwd`, while `echo` gives it 12 with the newline, so the server sees the password as `passwd\n` and answers 401.



## How Do You Send a Bearer Token With cURL?

Bearer tokens are sent with `curl -H "Authorization: Bearer $TOKEN" URL` or `curl --oauth2-bearer "$TOKEN" URL`. As we've discovered, Basic auth just means "here's my username and password", however sometimes that is not what the server wants to see.

Often, modern APIs use Bearer tokens to authenticate their clients, which means whoever holds the token gets in, so the token itself is the credential. Usually it comes from the API's login or token endpoint. Common examples are OAuth 2.0 access tokens, personal access tokens and JWTs.

### Should You Use -H or --oauth2-bearer?

Both options send the same line. If we run httpbin.dev/bearer with `--oauth2-bearer` and `-v`, filtered down to the header and the response, we can see the header curl generates for us:

shell

```shell
$ curl -sv --oauth2-bearer my-token-123 https://httpbin.dev/bearer 2>&1 | grep -E '^> Authorization|authenticated|"token"'
> Authorization: Bearer my-token-123
  "authenticated": true,
  "token": "my-token-123"
```



As you can see above, we used `--oauth2-bearer` for this request, while the `Authorization: Bearer my-token-123` header itself was generated by curl. `-H` on the other hand is the one to use for other scheme names like `Token` or a custom one, but for now most Bearer APIs can work well with either of them (the format itself is in [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750))!

Even though httpbin.dev accepts any token, it still needs one - leaving the header out or sending `Authorization: Bearer` with nothing after it (like an empty `$TOKEN` would) gets a 401 both times:

shell

```shell
$ curl -s -o /dev/null -w '%{http_code}\n' https://httpbin.dev/bearer
401
$ curl -s -o /dev/null -w '%{http_code}\n' -H "Authorization: Bearer" https://httpbin.dev/bearer
401
```



### How Do You Pass a Token From a Variable Without Breaking It?

In this example we're using httpbin.dev again, as it echoes the token back and we can see what double quotes (which expand `$TOKEN`) and single quotes (which don't) actually send:

shell

```shell
$ TOKEN=my-token-123
$ curl -H 'Authorization: Bearer $TOKEN' https://httpbin.dev/bearer
{
  "authenticated": true,
  "token": "$TOKEN"
}
$ curl -H "Authorization: Bearer $TOKEN" https://httpbin.dev/bearer
{
  "authenticated": true,
  "token": "my-token-123"
}
```



httpbin.dev accepts any token, so both requests get a 200 here, however an API that checks the token would reject the first one.

We could also skip the quotes and pass the header as is:

shell

```shell
$ curl -sS -H Authorization: Bearer $TOKEN https://httpbin.dev/bearer
curl: (6) Could not resolve host: Bearer
curl: (6) Could not resolve host: my-token-123
```



As you can see, the shell split the header at the spaces and curl tried `Bearer` and the token as two extra hosts. What about a token that works when pasted but fails from a variable? The asker in this [Stack Overflow question](https://stackoverflow.com/questions/71450063/bearer-token-as-variable-in-curl) got a 200 with the pasted token and `HTTP/1.1 400 Bad EOL` from the variable, and the accepted answer traced it to a line ending. Let's put a Windows line ending into `$TOKEN` and print every character with `od -c`:

shell

```shell
$ TOKEN=$(printf 'my-token-123\r\n')
$ printf '%s' "$TOKEN" | od -c
0000000    m   y   -   t   o   k   e   n   -   1   2   3  \r
0000015
```



As you can see, `$( )` stripped the `\n` but the `\r` is still there right after `my-token-123`, which curl would send along as is, so let's strip it ourselves with `tr`:

shell

```shell
$ TOKEN=$(printf '%s' "$TOKEN" | tr -d '\r')
$ printf '%s' "$TOKEN" | od -c
0000000    m   y   -   t   o   k   e   n   -   1   2   3
0000014
```



If we run `od -c` again we can see only the 12 characters of `my-token-123` and nothing after them.

[How to POST JSON With cURL in 2026: Inline, File, and jqSend JSON with cURL using --json, files, and stdin, add Bearer auth, parse responses with jq, and fix 400, 401, and 415 errors.](https://scrapfly.io/blog/posts/how-to-curl-json)



## How Do You Keep Passwords and Tokens Out of Your Shell History?

To keep passwords and tokens out of shell history, we need to keep them off the command line first. This is rather simple: curl can ask us for the password at a prompt, or read the secret from a `.netrc` file, a header file or an environment variable - so it never ends up in our history or the process list!

The [curl man page](https://curl.se/docs/manpage.html) says hiding the `-u` argument from process listings "is not enough to protect credentials", so the secret has to come from somewhere else. There are a few ways curl can do that, so let's take a look at them:

| Method | Command | Where the secret lives |
|---|---|---|
| Prompt | `curl -u user URL` | typed at the prompt |
| `.netrc` | `curl --netrc-file ./netrc URL` (or `-n` for `~/.netrc`) | file, `chmod 600` |
| Header file | `curl -H @auth-headers.txt URL` | file with `Authorization: Bearer ...` |
| Config file | `curl -K api.curlrc URL` | file with `header = "..."` or `user = "..."` |
| Environment variable | `curl --variable %TOKEN --expand-header "Authorization: Bearer {{TOKEN}}" URL` | `TOKEN` in the environment |

Let's take a quick look at how we can use `.netrc` first - it's one line per host, so we'll write one for httpbin.dev, lock it down (curl doesn't complain about file permissions, so this part is on us) and point curl at it:

shell

```shell
$ printf 'machine httpbin.dev login user password passwd\n' > netrc
$ chmod 600 netrc
$ curl --netrc-file ./netrc https://httpbin.dev/basic-auth/user/passwd
{
  "authorized": true,
  "user": "user"
}
```



As you can see, curl picked up the login and password from the file and httpbin.dev authorized us.

However, `.netrc` only knows logins and passwords - meaning our tokens have to live somewhere else. For this it might be worth putting the whole header into a file (`-H @file`) or a config file (`-K`), both of these authenticated against httpbin.dev/bearer just like our `-H` example.

So what about tokens that are already exported in our shell? For these we'll be sticking with `--variable` (added in curl 8.3.0) which imports the variable, and `--expand-header` which puts it into the header for us:

shell

```shell
$ export TOKEN=my-token-123
$ curl --variable %TOKEN --expand-header "Authorization: Bearer {{TOKEN}}" https://httpbin.dev/bearer
{
  "authenticated": true,
  "token": "my-token-123"
}
```



As you can see above, we used the `TOKEN` variable for this request, while the token itself never appeared in our command. If the variable isn't set or wasn't exported, curl will stop with `curl: Variable 'TOKEN' import fail, not set` rather than send an empty header.

That being said, Windows 10 and 11 ship with curl too (the [curl Windows page](https://curl.se/windows/microsoft.html) shows 8.13.0) and these options work the same there - only `export` is shell syntax, so PowerShell sets the variable with `$env:TOKEN = "..."`. In Windows PowerShell 5.1, type `curl.exe`, as plain `curl` is an alias for `Invoke-WebRequest` there.



## How Do You Send an API Key With cURL?

So how do we send an API key? As you might have guessed, it depends on the API - most of the time it's a custom header like `X-API-Key`, but some APIs want it in the `Authorization` header or as a URL query parameter.

Not all API keys are sent the same way, as there's no single standard for them - developers still [argue about the right header](https://softwareengineering.stackexchange.com/questions/353145/where-to-place-an-api-key-a-custom-http-header-vs-the-authorization-header-with).

In this example we're using httpbin.dev testing endpoint for headers, it returns the headers we sent as response body. If we send our key in a custom header, we can see it arrived as `X-Api-Key` (output trimmed to that header):

shell

```shell
$ curl -H "X-API-Key: abc123" https://httpbin.dev/headers
    "X-Api-Key": [
      "abc123"
    ],
```



On the other hand, the [Scrapfly Web Scraping API](https://scrapfly.io/products/web-scraping-api) takes the key as a `key` URL parameter (see the [getting started docs](https://scrapfly.io/docs/scrape-api/getting-started)) and a wrong one gets us a 401 error:

shell

```shell
$ curl "https://api.scrapfly.io/scrape?key=not-a-real-key&url=https://httpbin.dev/headers"
{"error_id":"b074510c-d19e-44a8-b596-749f8315ddb5","http_code":401,"message":"Invalid API key - make sure to provide it via `key` query parameter","reason":"Unauthorized"}
```



Since the key is part of the URL here, it's best to keep it in an environment variable (`SCRAPFLY_KEY`) rather than typing it out. Let's take a quick look at how we can send our own Bearer token to httpbin.dev/bearer through the API:

shell

```shell
$ curl -G https://api.scrapfly.io/scrape \
    --data-urlencode "key=$SCRAPFLY_KEY" \
    --data-urlencode "url=https://httpbin.dev/bearer" \
    --data-urlencode "headers[Authorization]=Bearer my-token-123"
```



Here, `-G` takes every `--data-urlencode` value and puts it into the URL as an encoded parameter, while `headers[Authorization]` tells the API which header to send to the page for us.

The API came back with `result.status_code` 200 and httpbin.dev's own answer in `result.content`: `{"authenticated": true, "token": "my-token-123"}` - so our token got through to the page just fine. That being said, when the page is loaded in a real browser (with `render_js`, or when the anti-bot bypass needs one), the docs only promise to pass on the `Cookie` and `Referer` headers.

[How Headers Are Used to Block Web Scrapers and How to Fix ItIntroduction to web scraping headers - what do they mean, how to configure them in web scrapers and how to avoid being blocked.](https://scrapfly.io/blog/posts/how-to-avoid-web-scraping-blocking-headers)



## When Do You Need --digest, --anyauth, NTLM or Negotiate?

Conveniently, a 401 response is supposed to come with a `WWW-Authenticate` header that indicates which authentication method the server wants (like Basic, Digest or NTLM - the last two mostly on appliances, Windows servers and older enterprise systems), so we only need these options when it asks for them. Alternatively, `--anyauth` can read this header and pick the method for us.

For example, if we're using httpbin.dev's Digest endpoint we can see it replies with `www-authenticate: Digest qop=auth, realm="httpbin", algorithm=MD5, ...` - in other words, our usual Basic credentials won't get us in:

shell

```shell
$ curl -s -o /dev/null -w '%{http_code}\n' -u user:passwd https://httpbin.dev/digest-auth/auth/user/passwd
401
$ curl -s -o /dev/null -w '%{http_code}\n' --digest -u user:passwd https://httpbin.dev/digest-auth/auth/user/passwd
200
$ curl -s -o /dev/null -w '%{http_code}\n' --anyauth -u user:passwd https://httpbin.dev/digest-auth/auth/user/passwd
200
```



As you can see above, the plain `-u` request was denied while `--digest` and `--anyauth` got through. Unfortunately, `--anyauth` costs an extra round trip (see `-v`): the first request is sent without an `Authorization` header and gets a 401, and only then curl sends a second one with `Authorization: Digest ...`. Note that the man page also advises against it for uploads from stdin as the data might need to be sent twice.

Unfortunately, NTLM and Negotiate are a bit more complicated and not easily testable as there's no public endpoint for them (`curl --version` shows whether our curl has them - look for `NTLM` or `SPNEGO` in the features line). NTLM (`--ntlm`) is an old Microsoft scheme which curl is dropping - the man page says NTLM support was removed in curl 8.24.0, so only 8.23.0 and older builds still have it. As for Negotiate (`--negotiate`), it needs curl built with GSS-API or SSPI and a fake `-u :` to work.

These are a few of the most important observations, for more see the curl project's own [HTTP authentication chapter](https://everything.curl.dev/http/auth.html).



Scrapfly

#### Scale your web scraping effortlessly

Scrapfly handles proxies, browsers, and anti-bot bypass — so you can focus on data.

[Try Free →](https://scrapfly.io/register)

## How Do You Log In With a Form and Reuse the Session Cookie?

Many web pages rely on cookies to track the login session instead of an `Authorization` header, which means we need to replicate this behavior in curl: we POST the login form with `-c jar.txt` to save the cookies and then send them back on later requests with `-b jar.txt`.

For example, web-scraping.dev's login form posts `username` and `password` to `/api/login`. Let's take a quick look at how we can log in, check the cookie and request the login page with it:

shell

```shell
$ curl -s -c jar.txt -d "username=user123&password=password" -o /dev/null -w '%{http_code}\n' https://web-scraping.dev/api/login
302
$ grep auth jar.txt
web-scraping.dev    FALSE   /   FALSE   0   auth    user123-secret-token
$ curl -s -b jar.txt https://web-scraping.dev/login | grep -o 'Logged in as[^<]*'
Logged in as User123
```



As you can see, the login replies with a 302 and its `Set-Cookie` header asks us to save `auth=user123-secret-token` for future requests - curl puts it in the jar and the next request comes back logged in! Without the cookie, the same `grep` finds nothing (if we already have the cookie value, `-b "auth=user123-secret-token"` works without a jar file).

[How to Handle Cookies in Web ScrapingIntroduction to cookies in web scraping. What are they and how to take advantage of cookie process to authenticate or set website preferences.](https://scrapfly.io/blog/posts/how-to-handle-cookies-in-web-scraping)



## Does cURL Send Your Authorization Header After a Redirect?

Not to another host. 300 range codes tend to mean redirection - in other words the server tells us our content was moved to a new location, and with `-L` curl follows it there. If this new location is on another host, scheme or port, curl drops both `-u` credentials and a custom `-H "Authorization: ..."` header unless we use `--location-trusted`.

This is important for APIs that redirect downloads or regions to another domain, and for any redirect we don't control. For example, httpbin.dev's `redirect-to` endpoint redirects us to web-scraping.dev, and with `-v` we can see which request carries the header:

shell

```shell
$ curl -sv -L -o /dev/null -H "Authorization: Bearer my-token-123" "https://httpbin.dev/redirect-to?url=https://web-scraping.dev/" 2>&1 | grep -E '^> (Host|Authorization)'
> Host: httpbin.dev
> Authorization: Bearer my-token-123
> Host: web-scraping.dev
$ curl -sv --location-trusted -o /dev/null -H "Authorization: Bearer my-token-123" "https://httpbin.dev/redirect-to?url=https://web-scraping.dev/" 2>&1 | grep -E '^> (Host|Authorization)'
> Host: httpbin.dev
> Authorization: Bearer my-token-123
> Host: web-scraping.dev
> Authorization: Bearer my-token-123
```



As you can see, the first request to httpbin.dev carries our header while the second one to web-scraping.dev doesn't - unless we use `--location-trusted`. `-u user:passwd` works the same way, and a same-host redirect (`redirect-to?url=https://httpbin.dev/headers`) keeps the header and echoes it straight back.

Unfortunately, the man page warns that `--location-trusted` "may or may not introduce a security breach", so it might be worth sticking to the default - if an API redirects us to a storage host that needs no credentials, the default is exactly what we want.

Note that proxies use their own options such as `--proxy-user`, for more see our cURL proxy guide.



## How Do You Debug a 401 Unauthorized Response in cURL?

What do we do when curl gets a 401? First, we take a look at what was actually sent: `-v` prints the `> Authorization:` line of our request along with the `WWW-Authenticate` header of the response, which tells us what scheme the server wants. So, to debug a 401 we compare these two with what the API expects.

For example, if we send nothing at all and use `-i` (which prints response headers along with the body), the server tells us exactly what it wants - output trimmed to the two lines that matter:

shell

```shell
$ curl -i https://httpbin.dev/basic-auth/user/passwd
HTTP/2 401
www-authenticate: Basic realm="Fake Realm"
```



As you can see, the server wants Basic authentication here (if it said `Digest` instead, we'd switch to `--digest` or `--anyauth`). Now, what if we do send something but it's wrong? Let's take the `echo` encoded credential from the Basic section and send it with `-v`:

shell

```shell
$ curl -sv -o /dev/null -H "Authorization: Basic dXNlcjpwYXNzd2QK" https://httpbin.dev/basic-auth/user/passwd 2>&1 | grep -iE "^> Authorization|^< HTTP|^< www-authenticate"
> Authorization: Basic dXNlcjpwYXNzd2QK
< HTTP/2 401
< www-authenticate: Basic realm="Fake Realm"
$ echo dXNlcjpwYXNzd2QK | base64 -d | od -c
0000000    u   s   e   r   :   p   a   s   s   w   d  \n
0000014
```



As you can see above, we sent our header with the right scheme for this request, while the server still answered with 401. If we decode it, there's a `\n` right after `passwd` which `echo` added before encoding - rebuilding it with `printf` fixes it (the `K` ending is specific to our `user:passwd` example though).

If the header looks right and the API still answers 401, the token itself might have expired and we should ask for a new one. A token without the needed scope usually gets a 403 instead, as [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750#section-3.1) recommends.

One more thing - the status-only checks we've used in this article are just `-o /dev/null -w '%{http_code}'`, which prints the status code and nothing else (`-w` alone would append it to the normal output). Adding `-sS` on top keeps scripts quiet except for errors.

[What is HTTP 401 Error and How to Fix itDiscover the HTTP 401 error meaning, its causes, and solutions in this comprehensive guide. Learn how 401 unauthorized errors occur.](https://scrapfly.io/blog/posts/what-is-http-401-error-and-how-to-fix-it)



## Power Up with Scrapfly



As you can see, authentication in cURL is quite simple until the website we're sending our credentials to doesn't want to be scraped. Here at ScrapFly we recognize the difficulties of web scraping and came up with an API solution that solves these issues for our users. ScrapFly is essentially an intelligent negotiator that sits between your scraper and your target - instead of connecting to the target itself, our curl command requests ScrapFly API to do it and simply returns the results.

This means we can keep using the same authentication details we've covered in this article. For example, the `headers[Authorization]` parameter from the API key section is passed on to the scraped page, and so is a `Cookie` header from a login form (when the page is loaded in a browser, with `render_js` or by the anti-bot bypass, only the `Cookie` and `Referer` headers are guaranteed to make it through).

ScrapFly can go even further and provides [anti scraping protection bypass](https://scrapfly.io/docs/scrape-api/unblocker), [javascript rendering](https://scrapfly.io/docs/scrape-api/javascript-rendering) through real browsers and [residential and datacenter proxies](https://scrapfly.io/docs/scrape-api/proxy) for targets that block plain curl.



## FAQ

Is Basic authentication with cURL secure?

The best way to keep Basic authentication secure is to only use it over HTTPS. Since Basic authentication only encodes the username and password with base64, anyone who can see our requests can decode them right back to `user:passwd`. In other words, over plain HTTP our password is basically sent as plain text!







What is the difference between -u and -H "Authorization: Basic ..."?

Nothing really, `-u` just does the base64 part for us. We can check it ourselves with `-v`:

shell

```shell
$ curl -sv -o /dev/null -u user:passwd https://httpbin.dev/basic-auth/user/passwd 2>&1 | grep "^> Authorization"
> Authorization: Basic dXNlcjpwYXNzd2Q=
$ curl -sv -o /dev/null -H "Authorization: Basic dXNlcjpwYXNzd2Q=" https://httpbin.dev/basic-auth/user/passwd 2>&1 | grep "^> Authorization"
> Authorization: Basic dXNlcjpwYXNzd2Q=
```









How do you send a Bearer token with a JSON POST in cURL?

Just like with any other request - `--json` sets the body along with the `Content-Type: application/json` header, while `-H "Authorization: Bearer $TOKEN"` adds our token on top:

shell

```shell
$ curl -s --json '{"a":1}' -H "Authorization: Bearer $TOKEN" https://httpbin.dev/post | grep -A2 -E '"(Authorization|Content-Type)"'
    "Authorization": [
      "Bearer my-token-123"
    ],
--
    "Content-Type": [
      "application/json"
    ],
```



For more on that see our [JSON with cURL guide](https://scrapfly.io/blog/posts/how-to-curl-json) which covers bodies, files and errors.









## Conclusion

In this article we've taken a look at the most common ways to authenticate with cURL - Basic auth, Bearer tokens, API keys, Digest and cookie based logins.

Plain curl is great for APIs that don't block it, however when the authenticated pages belong to a website we're scraping, dealing with blocking ourselves can be a painful experience. For this it might be worth taking a look into the [Scrapfly Web Scraping API](https://scrapfly.io/products/web-scraping-api) which forwards our `Authorization` header or cookies and handles proxies and anti-bot protection on top (when the page is loaded in a browser, with `render_js` or by the anti-bot bypass, only cookies are guaranteed to reach the page).



 

   [  Add as a preferred source ](https://google.com/preferences/source?q=scrapfly.io) Table of Contents















 

  Table of Contents

- [Key Takeaways](#key-takeaways)
- [How Do You Send an Authorization Header With cURL?](#how-do-you-send-an-authorization-header-with-curl)
- [How Does Basic Authentication Work in cURL?](#how-does-basic-authentication-work-in-curl)
- [How Do You Use -u or --user?](#how-do-you-use-u-or-user)
- [How Do You Build the Basic Authorization Header Yourself?](#how-do-you-build-the-basic-authorization-header-yourself)
- [How Do You Send a Bearer Token With cURL?](#how-do-you-send-a-bearer-token-with-curl)
- [Should You Use -H or --oauth2-bearer?](#should-you-use-h-or-oauth2-bearer)
- [How Do You Pass a Token From a Variable Without Breaking It?](#how-do-you-pass-a-token-from-a-variable-without-breaking-it)
- [How Do You Keep Passwords and Tokens Out of Your Shell History?](#how-do-you-keep-passwords-and-tokens-out-of-your-shell-history)
- [How Do You Send an API Key With cURL?](#how-do-you-send-an-api-key-with-curl)
- [When Do You Need --digest, --anyauth, NTLM or Negotiate?](#when-do-you-need-digest-anyauth-ntlm-or-negotiate)
- [How Do You Log In With a Form and Reuse the Session Cookie?](#how-do-you-log-in-with-a-form-and-reuse-the-session-cookie)
- [Does cURL Send Your Authorization Header After a Redirect?](#does-curl-send-your-authorization-header-after-a-redirect)
- [How Do You Debug a 401 Unauthorized Response in cURL?](#how-do-you-debug-a-401-unauthorized-response-in-curl)
- [Power Up with Scrapfly](#power-up-with-scrapfly)
- [FAQ](#faq)
- [Conclusion](#conclusion)
 
    Join the Newsletter  Get monthly web scraping insights 

 

  



Scale Your Web Scraping

Anti-bot bypass, browser rendering, and rotating proxies, all in one API. Start with 1,000 free credits.

  No credit card required  1,000 free API credits  Anti-bot bypass included 

 [Start Free](https://scrapfly.io/register) [View Docs](https://scrapfly.io/docs/onboarding) 

 Not ready? [Get our newsletter](#newsletter-modal) instead. 

 

 

## Related Articles

 [     

 http 

### What is HTTP 401 Error and How to Fix it

Discover the HTTP 401 error meaning, its causes, and solutions in this comprehensive guide. Learn how 401 unauthorized e...

 

 ](https://scrapfly.io/blog/posts/what-is-http-401-error-and-how-to-fix-it) [     

 curl 

### How to Use cURL GET Requests

Here's everything you need to know about cURL GET requests and some common pitfalls you should avoid.

 

 ](https://scrapfly.io/blog/posts/how-to-use-curl-get-requests) [     

 curl 

### How to POST JSON With cURL in 2026: Inline, File, and jq

Send JSON with cURL using --json, files, and stdin, add Bearer auth, parse responses with jq, and fix 400, 401, and 415 ...

 

 ](https://scrapfly.io/blog/posts/how-to-curl-json) 

  

## Related Questions

- [ Q How to Set cURL Authentication - Full Examples Guide ](https://scrapfly.io/blog/answers/how-to-set-authorization-with-curl-full-examples-guide)
- [ Q How to Persist Sessions Across Scrapy Requests ](https://scrapfly.io/blog/answers/persist-sessions-across-scrapy-requests)
- [ Q How to select dictionary key recursively in Python? ](https://scrapfly.io/blog/answers/how-to-select-dictionary-key-recursively-in-python)
- [ Q How to Send a HEAD Request With cURL? ](https://scrapfly.io/blog/answers/how-to-send-curl-head-requests)
 
  



   



 Scale your web scraping effortlessly, **1,000 free credits** [Start Free](https://scrapfly.io/register)