Home > Mobile >  How is -u of curl request is accessed in node js request message?
How is -u of curl request is accessed in node js request message?

Time:05-04

I have curl request as below,

curl -u user:password http://localhost:3000/user

How do I access the user and password passed in the http request on the server?

CodePudding user response:

The option -u specifies the username and password for the HTTP Basic Authentication.

It is accessible via the Request-Header Authorization (req.headers.authorization), but is encoded with base64.

The below code will read the header and decode the string, and then store the username and the password in seperate variables.

const b64auth = (req.headers.authorization || '').split(' ')[1] || ''
const strauth = Buffer.from(b64auth, 'base64').toString()
const splitIndex = strauth.indexOf(':')
const login = strauth.substring(0, splitIndex)
const password = strauth.substring(splitIndex   1)

For more information see Basic HTTP authentication with Node and Express 4

  • Related