According to this guide i have successfully create JWT for Google service account using Java example and it's worked. However, these lines are still "magical" for me:
GoogleCredential credential = GoogleCredential.fromStream(resourceAsStream);
PrivateKey privateKey = credential.getServiceAccountPrivateKey();
But i can't repeat it using Node.js. Postman says "Could not get any response".
Here is my code.
const jwt = require('jsonwebtoken');
const TOKEN_DURATION_IN_SECONDS = 3600;
const issueJWT = (
issuedAt = Math.floor(Date.now() / 1000),
serviceAccount = require('path/to/service-account.json')
) =>
jwt.sign(
{
'iss': serviceAccount.client_email,
'sub': serviceAccount.client_email,
'aud': `https://${SERVICE_NAME}/${API_NAME}`,
'iat': issuedAt,
'exp': issuedAt + TOKEN_DURATION_IN_SECONDS,
},
serviceAccount.private_key,
{
algorithm: 'RS256',
header: {
'kid': serviceAccount.private_key_id,
'typ': 'JWT',
'alg': 'RS256',
},
}
);
Onlinde decoder show same header and body for tokens created using Node.js and Java.
So, i assume that signatures are different.
Via jwt from java:
curl --header "Authorization: Bearer {jwt-from-java}" https://bigtableadmin.googleapis.com/v2/projects/{project-name}/instances -v
>
* schannel: client wants to read 102400 bytes
* schannel: encdata_buffer resized 103424
* schannel: encrypted data buffer: offset 0 length 103424
* schannel: encrypted data got 836
* schannel: encrypted data buffer: offset 836 length 103424
* schannel: decrypted data length: 773
* schannel: decrypted data added: 773
* schannel: decrypted data cached: offset 773 length 102400
* schannel: encrypted data length: 34
* schannel: encrypted data cached: offset 34 length 103424
* schannel: decrypted data length: 5
* schannel: decrypted data added: 5
* schannel: decrypted data cached: offset 778 length 102400
* schannel: encrypted data buffer: offset 0 length 103424
* schannel: decrypted data buffer: offset 778 length 102400
* schannel: schannel_recv cleanup
* schannel: decrypted data returned 778
* schannel: decrypted data buffer: offset 0 length 102400
< HTTP/1.1 200 OK
< Content-Type: application/json; charset=UTF-8
< Vary: X-Origin
< Vary: Referer
< Date: Sat, 21 Jul 2018 00:11:31 GMT
< Server: ESF
< Cache-Control: private
< X-XSS-Protection: 1; mode=block
< X-Frame-Options: SAMEORIGIN
< X-Content-Type-Options: nosniff
< Alt-Svc: quic=":443"; ma=2592000; v="44,43,39,35"
< Accept-Ranges: none
< Vary: Origin,Accept-Encoding
< Transfer-Encoding: chunked
<
{
"instances": [
...
]
}
* Connection #0 to host bigtableadmin.googleapis.com left intact
Via jwt from node.js:
curl --header "Authorization: Bearer {jwt-from-node}" https://bigtableadmin.googleapis.com/v2/projects/{project-name}/instances -v
>
* schannel: client wants to read 102400 bytes
* schannel: encdata_buffer resized 103424
* schannel: encrypted data buffer: offset 0 length 103424
* schannel: encrypted data got 836
* schannel: encrypted data buffer: offset 836 length 103424
* schannel: decrypted data length: 773
* schannel: decrypted data added: 773
* schannel: decrypted data cached: offset 773 length 102400
* schannel: encrypted data length: 34
* schannel: encrypted data cached: offset 34 length 103424
* schannel: decrypted data length: 5
* schannel: decrypted data added: 5
* schannel: decrypted data cached: offset 778 length 102400
* schannel: encrypted data buffer: offset 0 length 103424
* schannel: decrypted data buffer: offset 778 length 102400
* schannel: schannel_recv cleanup
* schannel: decrypted data returned 778
* schannel: decrypted data buffer: offset 0 length 102400
< HTTP/1.1 401 Unauthorized
< WWW-Authenticate: Bearer realm="https://accounts.google.com/"
< Vary: X-Origin
< Vary: Referer
< Content-Type: application/json; charset=UTF-8
< Date: Sat, 21 Jul 2018 00:08:58 GMT
< Server: ESF
< Cache-Control: private
< X-XSS-Protection: 1; mode=block
< X-Frame-Options: SAMEORIGIN
< X-Content-Type-Options: nosniff
< Alt-Svc: quic=":443"; ma=2592000; v="44,43,39,35"
< Accept-Ranges: none
< Vary: Origin,Accept-Encoding
< Transfer-Encoding: chunked
<
{
"error": {
"code": 401,
"message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED"
}
}
* Connection #0 to host bigtableadmin.googleapis.com left intact
How can i create JWT for Google service account using Node.js?
So from the error message it looks like this is not a JWT specific issue. This Google Groups post shows that the issue is due an incorrect CURL command being used. Check the curl command syntax and access token placement to make sure it is valid.
Suddenly, now it's works without any changes in code.
Related
* Trying 172.28.1.11:443... * TCP_NODELAY set * Connected to local.accounts.tandfeditingservices.com (172.28.1.11) port 443 (#0) * ALPN, offering http/1.1 * successfully set certificate verify locations: * CAfile: /etc/ssl/certs/ca-certificates.crt CApath: /etc/ssl/certs * SSL connection using TLSv1.2 / ECDHE-RSA-AES256-GCM-SHA384 * ALPN, server accepted to use http/1.1 * Server certificate: * subject: O=mkcert development certificate; OU=sanketm#SANKETM (SANKET MORE) * start date: Jun 1 00:00:00 2019 GMT * expire date: Sep 28 10:43:11 2032 GMT * issuer: O=mkcert development CA; OU=sanketm#SANKETM (SANKET MORE); CN=mkcert sanketm#SANKETM (SANKET MORE) * SSL certificate verify result: unable to get local issuer certificate (20), continuing anyway. > POST /oauth/token HTTP/1.1 Host: local.accounts.tandfeditingservices.com User-Agent: GuzzleHttp/7 Content-Type: application/x-www-form-urlencoded Content-Length: 135 * upload completely sent off: 135 out of 135 bytes * Mark bundle as not supporting multiuse < HTTP/1.1 200 OK < Server: nginx/1.18.0 (Ubuntu) < Content-Type: application/json; charset=UTF-8 < Transfer-Encoding: chunked < Connection: keep-alive < X-Powered-By: PHP/8.0.7 < pragma: no-cache < Cache-Control: no-store, private < Date: Wed, 28 Sep 2022 10:44:54 GMT < X-RateLimit-Limit: 500 < X-RateLimit-Remaining: 499 < Strict-Transport-Security: max-age=15768000; includeSubDomains < * Connection #0 to host local.accounts.tandfeditingservices.com left intact
I am getting above message during any virtual domain network call on localhost. I dig around it so come to know it is regarding SSL certicate. But when I checked the certificate with openssl s_client -connect local.api.com:443 -CAfile /etc/ssl/certs/ca-certificates.crt. It showing the correct result as Verify return code: 0 (ok)
Any help or guidance will be helpful.
Here is the source URL of the image -
https://erp.guu-portal.de/erp/dokumente/download/759927?filename=9783835408241.jpg
curl result for the image file -
curl -v 'https://erp.guu-portal.de/erp/dokumente/download/759927?filename=9783835408241.jpg'
* Trying 62.245.203.125:443...
* Connected to erp.guu-portal.de (62.245.203.125) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
* CAfile: /etc/ssl/cert.pem
* CApath: none
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* TLSv1.2 (IN), TLS handshake, Server hello (2):
* TLSv1.2 (IN), TLS handshake, Certificate (11):
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
* TLSv1.2 (IN), TLS handshake, Server finished (14):
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
* TLSv1.2 (OUT), TLS change cipher, Change cipher spec (1):
* TLSv1.2 (OUT), TLS handshake, Finished (20):
* TLSv1.2 (IN), TLS change cipher, Change cipher spec (1):
* TLSv1.2 (IN), TLS handshake, Finished (20):
* SSL connection using TLSv1.2 / ECDHE-RSA-AES256-GCM-SHA384
* ALPN, server accepted to use http/1.1
* Server certificate:
* subject: CN=*.guu-portal.de
* start date: Jan 5 00:00:00 2021 GMT
* expire date: Feb 5 23:59:59 2022 GMT
* subjectAltName: host "erp.guu-portal.de" matched cert's "*.guu-portal.de"
* issuer: C=GB; ST=Greater Manchester; L=Salford; O=Sectigo Limited; CN=Sectigo RSA Domain Validation Secure Server CA
* SSL certificate verify ok.
> GET /erp/dokumente/download/759927?filename=9783835408241.jpg HTTP/1.1
> Host: erp.guu-portal.de
> User-Agent: curl/7.77.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Date: Fri, 14 Jan 2022 17:55:16 GMT
< Server: Apache-Coyote/1.1
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: SAMEORIGIN
< Last-Modified: Thu, 18 Oct 2018 20:32:21 GMT
< Content-Disposition: attachment; filename=9783835408241.jpg
< Content-Type: image/jpeg;charset=UTF-8
< Content-Length: 182163
< Set-Cookie: JSESSIONID=30BDB73806080AEF778934ABEBADFFCE.worker1; Path=/erp; HttpOnly
<
Warning: Binary output can mess up your terminal. Use "--output -" to tell
Warning: curl to output it to your terminal anyway, or consider "--output
Warning: <FILE>" to save to a file.
* Failure writing output to destination
* Closing connection 0
* TLSv1.2 (OUT), TLS alert, close notify (256):
I was sending payload in post request -
payload = {'image': {'src': 'https://erp.guu-portal.de/erp/dokumente/download/759927?filename=9783835408241.jpg', 'filename': '399_1.jpg'}}
Posting images to rest API URL -
requests.session.put(base_url + f"products/{product_id}.json",payload))
Response:
Status Code 422 with Message: {"errors":{"image":["Could not process image: [\"\/erp\/dokumente\/download\/759927 (image\/jpeg;charset=UTF-8) is not a recognized format\"]"]}}
I have tried other public images and they work... however, they had content-type image/jpeg only
Here is the tutorial that I am following: What is the best way to enable a website users send money to each other?
The problem is with my post request.
Let's break it down into pieces.
Headers
headers: {
"Authorization": `Bearer ${accessToken}`,
"Content-Type": "application/json"
}
I get the access token also via paypal api namely https://api.sandbox.paypal.com/v1/oauth2/token.
Body
body: {
intent: 'CAPTURE',
purchase_units: [{
amount: {
currency_code: 'USD',
value: '2.00'
},
payee: {
email_address: "myanothersandboxaccount#gmail.com"
}
}]
}
But, it doesn't work, as I get an error
{
name: 'INVALID_REQUEST',
message: 'Request is not well-formed, syntactically incorrect, or violates schema.',
debug_id: '2884e1b5eccee',
details: [
{
field: '/',
location: 'body',
issue: 'INVALID_SYNTAX',
description: 'MALFORMED_REQUEST_JSON'
}
],
links: [
{
href: 'https://developer.paypal.com/docs/api/orders/v2/#error-INVALID_SYNTAX',
rel: 'information_link',
encType: 'application/json'
}
]
}
curl request
curl -v -X POST https://api.sandbox.paypal.com/v2/checkout/orders \
-H "Content-Type: application/json" \
-H "Authorization: Bearer A23AALAej8Yg-4iKJBcWckiv5-ZlhYWlkmBsPuWaVngJcMigU7P-6f8P02vnOpIo8QlOJ-P3hd3K86vKo_lpSlu0-bZBj98eg" \
-d '{
"intent": "CAPTURE",
"purchase_units": [
{
"amount": {
"currency_code": "USD",
"value": "100.00"
},
"payee": {
"email": "myanothersandboxaccount#gmail.com"
}
}
]
}'
curl response
Note: Unnecessary use of -X or --request, POST is already inferred.
* Trying 173.0.82.78...
* TCP_NODELAY set
* Connected to api.sandbox.paypal.com (173.0.82.78) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
* CAfile: /etc/ssl/cert.pem
CApath: none
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* TLSv1.2 (IN), TLS handshake, Server hello (2):
* TLSv1.2 (IN), TLS handshake, Certificate (11):
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
* TLSv1.2 (IN), TLS handshake, Request CERT (13):
* TLSv1.2 (IN), TLS handshake, Server finished (14):
* TLSv1.2 (OUT), TLS handshake, Certificate (11):
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
* TLSv1.2 (OUT), TLS change cipher, Change cipher spec (1):
* TLSv1.2 (OUT), TLS handshake, Finished (20):
* TLSv1.2 (IN), TLS change cipher, Change cipher spec (1):
* TLSv1.2 (IN), TLS handshake, Finished (20):
* SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256
* ALPN, server did not agree to a protocol
* Server certificate:
* subject: C=US; ST=California; L=San Jose; O=PayPal, Inc.; OU=PayPal Production; CN=api.sandbox.paypal.com
* start date: Jul 27 00:00:00 2020 GMT
* expire date: Aug 1 12:00:00 2022 GMT
* subjectAltName: host "api.sandbox.paypal.com" matched cert's "api.sandbox.paypal.com"
* issuer: C=US; O=DigiCert Inc; OU=www.digicert.com; CN=DigiCert SHA2 High Assurance Server CA
* SSL certificate verify ok.
> POST /v2/checkout/orders HTTP/1.1
> Host: api.sandbox.paypal.com
> User-Agent: curl/7.64.1
> Accept: */*
> Content-Type: application/json
> Authorization: Bearer A23AALAej8Yg-4iKJBcWckiv5-ZlhYWlkmBsPuWaVngJcMigU7P-6f8P02vnOpIo8QlOJ-P3hd3K86vKo_lpSlu0-bZBj98eg
> Content-Length: 212
>
* upload completely sent off: 212 out of 212 bytes
< HTTP/1.1 201 Created
< Cache-Control: max-age=0, no-cache, no-store, must-revalidate
< Content-Length: 501
< Content-Type: application/json
< Date: Sat, 05 Dec 2020 10:30:13 GMT
< Paypal-Debug-Id: 6bd069526af1c
<
* Connection #0 to host api.sandbox.paypal.com left intact
{"id":"674004650C383744Y","status":"CREATED","links":[{"href":"https://api.sandbox.paypal.com/v2/checkout/orders/674004650C383744Y","rel":"self","method":"GET"},{"href":"https://www.sandbox.paypal.com/checkoutnow?token=674004650C383744Y","rel":"approve","method":"GET"},{"href":"https://api.sandbox.paypal.com/v2/checkout/orders/674004650C383744Y","rel":"update","method":"PATCH"},{"href":"https://api.sandbox.paypal.com/v2/checkout/orders/674004650C383744Y/capture","rel":"capture","method":"POST"}]}* Closing connection 0
And, with curl I get a successful response. I can see that all went well from my paypal sandbox dashboard.
What could it be?
I was using node-fetch to call the paypal api to create an order. Tried with axios, worked just fine.
The error basically means PayPal isn't able to parse the body object it received as JSON, so it appears something is being transmitted/received incorrectly.
You should first test with command-line curl to verify functionality and your JSON's correctness, which should work.
Then to get more details about what's actually going wrong in what you are sending, you will need to log the actual data being sent (not your code, the actual data the code sends when executed)
One way to do this is to instead of sending your request to https://api-m.paypal.com , instead send it to a request bin service like offered via https://requestbin.com/
I have a Tomcat app configured with Azure ADFS SSO over SAML. SSO is working, however I now need to access my Tomcat app via restful API with Azure ADFS SSO.
I was able to get access token from Azure AD SSO by doing
curl -X POST -d 'grant_type=client_credentials&client_id=<APP_ID>&client_secret=<PASSWORD>&resource=https%3A%2F%2Fmanagement.azure.com%2F' https://login.microsoftonline.com/<TENANT_ID>/oauth2/token | jq .
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 1592 100 1420 100 172 3169 383 --:--:-- --:--:-- --:--:-- 3553
{
"token_type": "Bearer",
"expires_in": "3599",
"ext_expires_in": "3599",
"expires_on": "1592338746",
"not_before": "1592334846",
"resource": "https://management.azure.com/",
"access_token": "MY_TOKEN"
}
If I don't have SSO turn on, I would usually create seesion cookie in my Tomcat app doing this
curl -v -k -X POST 'https://<HOSTNAME>/<APP>/j_spring_security_check?j_username=<USERNAME>&j_password=<PASSWORD>' -c ./cookie.txt
I've tried passing token as header, but didn't work
curl -v -k -X POST 'https://<HOSTNAME>/<APP>/j_spring_security_check?j_username=<USERNAME>&j_password=<PASSWORD>' -c ./cookie.txt --header "Authorization: Bearer MY_TOKEN"
Cookie.txt created.
Then I tried to call a GET API, didn't get the expected response JSON, but here is the verbose log from curl.
curl -v -k -X GET 'https://<HOSTNAME>/<APP>/source/v1/getSources?type=EXTERNAL&count=2&sortAttr=name&sortDir=ASC' -b ./cookie.txt | jq .
Note: Unnecessary use of -X or --request, GET is already inferred.
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- 0:00:04 --:--:-- 0* Trying 192.168.56.210...
* TCP_NODELAY set
0 0 0 0 0 0 0 0 --:--:-- 0:00:05 --:--:-- 0* Connected to HOSTNAME> (192.168.56.210) port 8443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
* CAfile: /etc/ssl/cert.pem
CApath: none
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
} [223 bytes data]
* TLSv1.2 (IN), TLS handshake, Server hello (2):
{ [81 bytes data]
* TLSv1.2 (IN), TLS handshake, Certificate (11):
{ [859 bytes data]
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
{ [333 bytes data]
* TLSv1.2 (IN), TLS handshake, Server finished (14):
{ [4 bytes data]
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
} [70 bytes data]
* TLSv1.2 (OUT), TLS change cipher, Change cipher spec (1):
} [1 bytes data]
* TLSv1.2 (OUT), TLS handshake, Finished (20):
} [16 bytes data]
* TLSv1.2 (IN), TLS change cipher, Change cipher spec (1):
{ [1 bytes data]
* TLSv1.2 (IN), TLS handshake, Finished (20):
{ [16 bytes data]
* SSL connection using TLSv1.2 / ECDHE-RSA-AES256-GCM-SHA384
* ALPN, server did not agree to a protocol
* Server certificate:
* subject: C=blah; ST=us; L=us; O=blah; OU=blah; CN=blah
* start date: Jun 16 14:21:29 2020 GMT
* expire date: Sep 14 14:21:29 2020 GMT
* issuer: C=blah; ST=us; L=us; O=blah; OU=blah; CN=blah
* SSL certificate verify result: self signed certificate (18), continuing anyway.
> GET /qdc/source/v1/getSources?type=EXTERNAL&count=2&sortAttr=name&sortDir=ASC HTTP/1.1
> Host: dfz.local:8443
> User-Agent: curl/7.64.1
> Accept: */*
> Cookie: JSESSIONID=1D244E5E4DBA30399E856E01909B0DDF
>
< HTTP/1.1 302 Found
< Server: Apache-Coyote/1.1
< Cache-control: no-cache, no-store
< Pragma: no-cache
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Strict-Transport-Security: max-age=31536000 ; includeSubDomains
< Location: https://login.microsoftonline.com/f08ee33a-102b-4180-998b-3fdd8acc49ab/saml2?SAMLRequest=hZLNTsMwEIRfxdp7EseJwLGaogJCIIGoSODAzXGc1lViF69TIZ6e0B8BFzhantnxzufZxfvQk532aJwtIY0pEG2Va41dlfBc30QcLuYzlEPPtmIxhrV90m%2BjxkAmo0VxuClh9FY4iQaFlYNGEZSoFg%2F3gsVUbL0LTrkeyAJR%2BzBFXTmL46B9pf3OKP38dF%2FCOoQtiiRpu4%2B4d0r2gud5lry1KvlKSarqEcj1FG2sDPvnnhy9WxkbD0Z5h64LzvbG6li5Ieko1zrLZJRS1kR5ymlUFLyJsq5tuVQqL2Szn86A3Div9H7FEjrZowZyd12C5Oema7rNmVkVWdqwRm1yzlKzWVNTZJMGlxLR7PS3C3HUdxaDtKEERhmN6FmU8pqlIqOC8pin2SuQ5bGXS2MPff9VYnMQobit62W0fKxqIC8nbpMAjpTEPt3%2FxPP3YHliAvP%2FCAw6yFYGOUt%2BRs2Px9%2F%2FY%2F4J&SigAlg=http%3A%2F%2Fwww.w3.org%2F2000%2F09%2Fxmldsig%23rsa-sha1&Signature=HcbOW7%2BIOjXNr73H%2BKRHEtIbjJGPHa5CsXCeoSzVMVf5lCu07AEtpVPZmVw9IViBZcniKqhnC2zokz6ZOtVehsuNcSLDWpqViLLRicqBtRenmfe9RL5vI%2BlpcdS92wRT44V%2FMH1t3y7lILea34sLP2ySz0XVORSxL7FzEade3Q72cHQyu1xBuFlf9x7BUjxe8ZO5rZeGFsq98AQ9IwZIlJ3%2Fs%2F8Kp3eexw%2BmfVRhLU7eNLefDX%2BMfux%2BHvlKVlQpI6iHR1LSIEcNXX6nV%2BEAt7oa20FBDXV0PSGBy8hcBgzyPLhwFMWhe5%2BzUt9ssL2IO9kk8loWBNQek6x%2Bmpzw5w%3D%3D
< Content-Length: 0
< Date: Thu, 18 Jun 2020 21:30:08 GMT
<
0 0 0 0 0 0 0 0 --:--:-- 0:00:05 --:--:-- 0
* Connection #0 to host dfz.local left intact
* Closing connection 0
Curl for client credential grant type
curl -X POST -d “grant_type=client_credentials&client_id=clientid&client_secret= secret&scope= https%3A%2F%2Fgraph.microsoft.com%2F.default” https://login.microsoftonline.com/tenantid/oauth2/v2.0/token
After getting the token use below query to pass the token in header
curl -H "Authorization: Basic <_your_token_>" http://www.example.com
For admin user:
$ curl -X POST localhost:5984/_session -d "username=admin&password=admin"
{"ok":true,"name":"admin","roles":["_admin"]}
$ curl -vX GET localhost:5984/_session --cookie AuthSession=YWRtaW...
{"ok":true,"userCtx":{"name":"admin","roles":["_admin"]},"info":{"authentication_db":"_users","authentication_handlers":["cookie","default"],"authenticated":"cookie"}}
but for regular user:
$ curl -vX POST localhost:5984/_session -d "username=user&password=123"
{"ok":true,"name":"user","roles":["users"]}
$ curl -vX GET localhost:5984/_session --cookie AuthSession=ZGlqbzo...
{"ok":true,"userCtx":{"name":null,"roles":[]},"info":{"authentication_db":"_users","authentication_handlers":["cookie","default"]}}
The same thing happens when im doing XmlHttpRequest via iron-ajax element, or simply from chrome. What am I doing wrong?
CouchDB version: 2.1.1
Config:
[chttpd]
bind_address = 0.0.0.0
port = 5984
authentication_handlers = {couch_httpd_auth, cookie_authentication_handler}, {couch_httpd_auth, default_authentication_handler}
[httpd]
enable_cors = true
[couch_httpd_auth]
allow_persistent_cookies = true
timeout = 60000
[cors]
credentials = true
origins = *
headers = accept, authorization, content-type, origin, referer
methods = GET, PUT, POST, HEAD, DELETE
I didn't quite get your problem, but here is what I do with curl to authenticate with cookie as a nonadmin user:
First I run curl with -v option to see the header fields:
$ curl -k -v -X POST https://192.168.1.106:6984/_session -d 'username=jan&password=****'
Note: Unnecessary use of -X or --request, POST is already inferred.
* Trying 192.168.1.106...
* Connected to 192.168.1.106 (192.168.1.106) port 6984 (#0)
* found 148 certificates in /etc/ssl/certs/ca-certificates.crt
* found 604 certificates in /etc/ssl/certs
* ALPN, offering http/1.1
* SSL connection using TLS1.2 / ECDHE_RSA_AES_128_GCM_SHA256
* server certificate verification SKIPPED
* server certificate status verification SKIPPED
* error fetching CN from cert:The requested data were not available.
* common name: (does not match '192.168.1.106')
* server certificate expiration date OK
* server certificate activation date OK
* certificate public key: RSA
* certificate version: #3
* subject: O=Tech Studio
* start date: Sat, 31 Mar 2018 04:37:51 GMT
* expire date: Tue, 30 Mar 2021 04:37:51 GMT
* issuer: O=Tech Studio
* compression: NULL
* ALPN, server did not agree to a protocol
> POST /_session HTTP/1.1
> Host: 192.168.1.106:6984
> User-Agent: curl/7.47.0
> Accept: */*
> Content-Length: 25
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 25 out of 25 bytes
< HTTP/1.1 200 OK
< Set-Cookie: AuthSession=amFuOjVBRTk3MENGOuKAb68qYzf5jJ7bIOq72Jlfw-Qb; Version=1; Secure; Path=/; HttpOnly
< Server: CouchDB/2.1.1 (Erlang OTP/18)
< Date: Wed, 02 May 2018 08:03:27 GMT
< Content-Type: application/json
< Content-Length: 44
< Cache-Control: must-revalidate
<
{"ok":true,"name":"jan","roles":["sample"]}
* Connection #0 to host 192.168.1.106 left intact
I see in the above header fields the cookie:
Set-Cookie: AuthSession=amFuOjVBRTk3MENGOuKAb68qYzf5jJ7bIOq72Jlfw-Qb; Version=1; Secure; Path=/; HttpOnly
I use the above cookie to authenticate as a nonadmin user and get the user info for the same nonadmin user like this:
$ curl -k -X GET https://192.168.1.106:6984/_users/org.couchdb.user:jan -H 'Cookie: AuthSession=amFuOjVBRTk3MENGOuKAb68qYzf5jJ7bIOq72Jlfw-Qb'
{"_id":"org.couchdb.user:jan","_rev":"3-f11b227a6e1236fa502af668fdbf326d","name":"jan","roles":["sample"],"type":"user","password_scheme":"pbkdf2","iterations":10,"derived_key":"a973123ebd9dbc2a543d477a506268b018e7aab4","salt":"0ef2111a894062b08ffd723fd34b6b75"}
Problem gone when i removed from my local.ini
authentication_handlers = {couch_httpd_auth, cookie_authentication_handler}, {couch_httpd_auth, default_authentication_handler}
Because i used incorrect handler: couch_httpd_auth in the config for chttpd, when that handler is only written to work with the original couch_httpd module