Skip to content

Instantly share code, notes, and snippets.

@tcrowe
Last active February 2, 2020 18:55
Show Gist options
  • Save tcrowe/c457027101be136b21f9bb9dd42f2663 to your computer and use it in GitHub Desktop.
Save tcrowe/c457027101be136b21f9bb9dd42f2663 to your computer and use it in GitHub Desktop.
npm auth token with zsh or bash and curl or node
// npm install superagent
const superagent = require("superagent");
// this is verdaccio's url ↓ but you could use like registry.npmjs.com if that is allowed in their TOS
const registryUrl = "http://127.0.0.1:4873";
const username = "myusername2";
const password = "mypassword2";
const frm ={
name: username,
password,
type: 'user'
};
const loginUrl = `${registryUrl}/-/user/org.couchdb.user:${username}`;
superagent
.put(loginUrl)
.type("json")
.accept("json")
.auth(username, password)
.send(frm)
.end(function(err, res) {
console.log("err", err)
console.log("res.body", res && res.body);
});
#!/bin/zsh
# inspired by this script
# https://stackoverflow.com/questions/23460980/set-up-npm-credentials-over-npm-login-without-reading-input-from-stdin
# and tvb user
# https://github.com/verdaccio/verdaccio/issues/490#issuecomment-358405862
# this is verdaccio's url ↓ but you could use like registry.npmjs.com if that is allowed in their TOS
registryUrl='http://127.0.0.1:4873'
registryHost='127.0.0.1:4873'
username='myusername'
password='mypassword'
form="""
{
\"name\": \"$username\",
\"password\": \"$password\",
\"type\": \"user\"
}
"""
TOKEN=$(curl -s \
-H "Accept: application/json" \
-H "Content-Type:application/json" \
-X PUT --data $form \
--user $username:$password \
$registryUrl/-/user/org.couchdb.user:$username 2>&1 | grep -Po \
'(?<="token": ")[^"]*')
echo "//$registryHost/:_authToken=$TOKEN" >> .npmrc
@tcrowe
Copy link
Author

tcrowe commented Feb 1, 2020

@orefalo issue and I were trying to automate the login for infrastructure purposes. The hidden part I couldn't see in the logs was it was doing HTTP basic auth. Like --user myuser:mypass in cURL. @tvb user already solved it in the past but we didn't see it right away. 🤕

(sorry if you didn't want to be @ -mentioned, very excite! 😅)

Using this technique npm install or other operations can be automated via buildbot, drone, jenkins, or other CI/CD.

→ ⭐️ if you like and enjoy 🤗 ←

➕Add more if you know them!

@orefalo
Copy link

orefalo commented Feb 2, 2020

Will give it a try, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment