NPM ERR Code E401: Unable to authenticate, need: Bearer authorization - node.js

I downloaded a NodeJS application from GitHub and facing the following error when executing npm install.
npm ERR! code E401
npm ERR! Unable to authenticate, need: Bearer authorization_uri=https://login.windows.net/c1156c2f-a3bb-4fc4-ac07-3eab96da8d10, Basic realm="https://pkgsprodeus21.pkgs.visualstudio.com/", TFS-Federated
My Node version is 6.13.1 and NPM version is 6.13.4.
Following is the content of package.json file:
{
"name": "DemoApp",
"version": "1.0.0",
"description": "A social oasis for lovers of pizza.",
"repository": "****",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"author": "****",
"license": "MIT",
"dependencies": {
"#hapi/boom": "7.4.2",
"#hapi/catbox": "10.2.1",
"#hapi/catbox-redis": "5.0.2",
"#hapi/cookie": "10.1.0",
"#hapi/good": "8.2.0",
"#hapi/good-squeeze": "5.2.0",
"#hapi/hapi": "18.3.1",
"#hapi/inert": "5.2.1",
"#hapi/joi": "15.1.0",
"#hapi/vision": "5.5.2",
"aws-sdk": "2.488.0",
"bcryptjs": "2.4.3",
"bootflat": "2.0.4",
"fs-extra": "8.1.0",
"handlebars": "4.1.2",
"lodash": "4.17.13",
"pg": "7.11.0",
"sequelize": "5.9.4"
}
}
I have been stuck at this issue since yesterday and still no luck finding the solution.
Any help would be highly appreciated.

This is what worked for me.
First, delete the .npmrc file in your Users folder. This folder:
C:\Users\[your user name]
Then run this command in your project folder that has an .npmrc file in it:
npx vsts-npm-auth -config .npmrc

Use npm install --registry https://registry.npmjs.org instead of npm install

No need to delete the .npmrc file, the following worked for me
npm logout
Then
vsts-npm-auth -config .npmrc

If you get E401 with a private npm registry after upgrading to npm v7, remove your package-lock.json and reinstall.
The registry url setting in .npmrc needs to match the http/https protocol in your package-lock.json exactly.
Or as Stuart pointed out: find and replace to update the existing lock file with the correct URL

Worked for me:
Delete the yarn.lock/package-lock.json files
npm install

I had the same issue, my discovery was as follows:
The application node.js version was 14.0
but the node version in my machine was 16.0.
I had to install the node the version 14.0 to resolve the issue.
To manage multiple node versions this tool is highly recommended.
windows - Nvm for windows
Linux - Nvm for Linux

I had this exactly same error and turned out it was an issue with personal access token (PAT). Renew your PAT and run vsts-npm-auth.

Delete old .npmrc file from user home directory and then run the following command
vsts-npm-auth -config .npmrc -T $HOME/.npmrc

This issue comes from a wrong configuration in your .npmrc file. I had a slightly different error so I'm sharing it here.
In my case the exact error was:
Unable to authenticate, need: Bearer realm="<registry>", Basic realm="<registry>"
My npmrc file should connect to a private npm registry and looked like this:
registry=https://<private-registry>
//<private-registry>:_authToken=<token>
//<private-registry>:always-auth=true
The issue was that I needed to add the https:// protocol also to the second and third line and it worked. In the end it looked like this:
registry=https://<private-registry>
//https://<private-registry>:_authToken=<token>
//https://<private-registry>:always-auth=true

I solved it running this command:
npm logout/npm login

I had the same error with our company registry configured in .npmrc
registry=https:<compnay-registry-url>
Node version : 16.10.0
NPM version : 7.24.0
Solution:
Execute npm login
$ npm login
npm notice Log in on https:<registry-url>
Username: xxxx
Password:
Email: (this IS public) (xxxx)
Logged in as xxx on https:<registry-url>.
After this .npmrc got updated with
//<registry-url>/:_authToken=xxxxx

If you are trying to install any package from your private repo and you are getting this error with npm i package_name command then
1. remove your package-lock.json from the the directory where to tried to create the package from
2. reinstall dependencies: npm i
this will resolve the issue.

I had the same issue caused by an expired token in the .npmrc file in my project directory. Sadly the error is very unspecific on what causes the auth error.

This worked for me. I just logged in again in NPM and the problem was solved
npm login
After u write your username and password execute again
npm install

For me the the problem was in .npmrc file the key password needed to be changed to _password then npm install worked.

Using a Mac and Azure - it was because my Personal Access Token (PAT) had expired and it didn't let me know.
Open your .npmrc with your auth tokens in.
Go to your azure repo and click your profile and then personal access tokens.
Create a new token.
Open terminal and run:
node -e "require('readline') .createInterface({input:process.stdin,output:process.stdout,historySize:0}) .question('PAT> ',p => { b64=Buffer.from(p.trim()).toString('base64');console.log(b64);process.exit(); })"
Paste your PAT in and press Enter
Copy the Base64 encoded value into your .npmrc password.

Had the same error.
In my case, the initial project including package-lock.json file was composed with NodeJS version 12 and npm version 6.
But trying to run npm install on my local machine with NodeJS version 16 and npm version 7 was causing this problem.
My solution was installing dependencies with the initial version of NodeJS. I used docker to get the correct version, run this command from the root directory of your project (where the package.json file is located):
docker run --rm -it \
-w /app \
-v $PWD/:/app \
node:12 \
npm install
If you do not have docker installed, you can try using nvm.

Related

E401 - Unable to authenticate, your authentication token seems to be invalid

I tested with Azure Packages private NPM server and now want to revert back to using the standard NPM registry but when I do it complains. I have tried everything I can think of and it is blocking me from doing any work now. I'd really appreciate any help.
The error
npm ERR! code E401
npm ERR! Unable to authenticate, your authentication token seems to be invalid.
npm ERR! To correct this please trying logging in again with:
npm ERR! npm login
If I check the log it is still, somehow, trying to find packages from Azure rather than the npm registry.
The Azure URL specified below doesnt exist in any .npmrc file or package-lock file I can find!
To be clear here I want to use the default NPM registry not Azure. e.g.
32 silly fetch manifest #types/angular#https://pkgs.dev.azure.com/***/***/_packaging/***.Common.UI/npm/registry/#types/angular/-/angular-1.6.45.tgz
Steps I have taken
Deleted my local .npmrc file
Deleted .npmrc file from my user profile
Cleared NPM cache
Cleared local node_modules folder
npm config set registry https://registry.npmjs.org/
npm config set registry https://registry.npmjs.com/
Reinstalled node.js
In each case, running npm install still gives me the same error.
Please help!
.npmrc containing private repo credentials
I had similar error. It turned out that I've saved some credentials for private repo on .npmrc file at the root of my home folder.
So when I did npm install on my project, I get package-lock.json file contents appended with the private repo url. So this was the source of the error when deploying the project.
What I did was to temporarily remove the .npmrc, delete package-lock.json, delete node_modules and re-run npm install.
In my case the private repo details was not relevant for the project(so deleting .npmrc was not an issue)
Check your package.json for the node version you should be using and make sure that you are using a compatible version with nvm or something. This has been consistently the reason I have seen this error lately on my own machine.
In my case , I just deleted the package-lock.json file and tried running npm install.
The error disappeared and all packages in node-modules were created.
This happened because in the previous package-lock.json file the resolved field had an address that was not for public access.
But my new package-lock.json resolved field looks like this:
"node_modules/#hapi/hoek": {
"version": "9.3.0",
"resolved": "https://registry.npmjs.org/#hapi/hoek/-/hoek-9.3.0.tgz",
"integrity": "sha512-/c6rf4UJlmHlC9b5BaNvzAcFv7HZ2QHaV0D4/HNlBdvFnvQq8RI4kYdhyPCl7Xj+oWvTWQ8ujhqS53LIgAe6KQ=="
}.
Tried all the methods but Nothing worked for me. This steps solved my issue.
Delete the .npmrc file in your Users folder.
C:\Users\[your user name]
2.Run this command in your project folder that has an .npmrc file in it:
npx vsts-npm-auth -config .npmrc
The credentials in the .npmrc file have an expiration time. You need to regenerate these credentials.
Had similar issue, Deleting the .npmrc and then doing npm login again solved my issue, it was located in the project directory
Above #kotana Sie worked for me. But there is no explanation so I would like to add that.
the errors mean that your access key to the private Azure DevOps npm repository has expired and npm can’t login to the repository using it.
To refresh the keys just run to acquire new:
vsts-npm-auth -config .npmrc
There is a known issue with sometimes that doesn't work and just says the keys “are already up to date” or “can’t get an authentication token…”:. To solve it delete the C:\Users\<YourAccountName>\.npmrc manually and repeat the process.

npm error E401: Unable to authenticate, need: BASIC realm="Sonatype Nexus Repository Manager"

I upgraded node version to 12.16.2 and npm version to 6.14.4. After that I am not able to run npm install, as I'm getting this error
code E401
npm ERR! Unable to authenticate, need: BASIC realm="Sonatype Nexus Repository Manager"
I even tried deleting node_modules and package-lock.json and running npm install again, but doesn't change anything.
I had similar issue. I resolved it by adding _auth into my ~/.npmrc. See the doc how to encode your nexus credential. I added the encoded credential using npm config set _auth xxx.
You wont be able to see the value using npm config list or npm config get _auth.
In my case, the problem was I've entered another registry address in same Nexus for npm login command.
npm login --registry=http://nexus_url:port/repository/wrong_address
My problem was solved by logging into correct address:
npm login --registry=http://nexus_url:port/repository/correct_address
what worked for me is :
I deleted the .npmrc file under C/users/ folder.
and ran npx vsts-npm-auth -config .npmrc command to create a new file in the users folder
Deleted the .npmrc file under C/users/ folder
npm set registry=http....
npm set _auth=(login:pass in base64):
I found a way out. With this new npm version they are enforcing authentication to access certain packages. We realised we don't need to use authentication for any of the packages we were downloading, hence the auth code we had was unnecessary. So we just removed it and it all worked.
vsts-npm-auth -config .npmrc -F
Is the only solution I found;
Edit: make sure to run npm install -g vsts-npm-auth before
You can remove package-lock.json .. it works with me
I'm run set's command from the post and add in nexus "Active realms" profile "npm Bearer Token Realm". Links: https://help.sonatype.com/repomanager3/system-configuration/access-control/realms
My problem was solved.
I encountered this error when running an npm install that was pulling some dependencies from a non-public registry located on a self-hosted Azure DevOps (AzDo) server.
I had a .npmrc file in the project, and a .npmrc file in my user profile dir with an AzDo personal access token (PAT) that had allowed access previously. The AzDo UI reported my token as still being valid.
PS C:\src\app> npm install
npm ERR! code E401
npm ERR! Unable to authenticate, need: Basic realm="{INTERNAL_REGISTRY_URL}", Negotiate, NTLM
In my case, the solution was to regenerate the AzDo PAT and update the .npmrc found in my user profile directory.
What worked for me was running npm login, then entering my Username, Password, and Email to log in to the registry defined in .npmrc. I then proceeded with npm installing the packages I needed and it worked.
Had the same issue while doing npm i for a private npm registry. Solved it by removing the _authToken parameter from some lines in my .npmrc file in my user's root directory:
Before:
//registry.npm.example.com/:_authToken=NpmToken.XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXX
//npm.artifacts.example.io/:_authToken=NpmToken.XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXX
update-notifier=false
registry=https://npm.artifacts.example.io/
After:
//registry.npm.example.com/
//npm.artifacts.example.io/
update-notifier=false
registry=https://npm.artifacts.example.io/
In my case the Nexus Authentication and project I am using requires Node version: 12.8.1.
I was using node version: 16.13.2
I use NVM to install 12.8.1 with nvm install 12.8.1
Then nvm use 12.8.1
This will now work on my machine and environment.
if the .npmrc file config like this
//registry.npm.example.com/:_auth="base64(username:psw)"
try this
//registry.npm.example.com/:_authToken="base64(username:psw)"
In my case, npmjs expected a Base64 encoded Personal Access Token in the .npmrc file, and I had forgotten to Base64 encode it before pasting it into the user .npmrc file.
You can try downgrading the current node version, 16, to 14.20.0.
My steps to fix this issue.
Earlier I had configured NODE_HOME under "Environment variable".
I removed it.
Only configured the path.
Created a new folder in the "C" drive and pasted the node files.
(System variable)Path = "C:\Node\node-v14.20.0-win-x64"
I had same issue as I had configured my auth through the .npmrc file by adding the below details to it:
_auth=xxx
always-auth=true
email=example#mail.com
The error was:
npm ERR! code E401
npm ERR! Unable to authenticate, need: BASIC realm="Sonatype Nexus Repository Manager"
then got resolved after removing underscore (_) from auth in the .npmrc file:
auth=xxx
always-auth=true
email=example#mail.com

Authentication error on publishing to private NPM repository on Nexus

I am having authentication problem when publishing to my private npm registry hosted on my private Nexus.
My Nexus setup is I have npm-proxy, npm-registry (hosted npm with allowRepublish=false), npm-snapshots (hosted npm with allowRepublish=true) and npm-public (group with all other three repositories).
Since I am developing a library, I am using my snapshot repository, so I can redeploy same version constantly (something like snapshot in maven world).
In my library project I have set this option in package.json
"publishConfig": {
"registry": "https://my.nexus.com/repository/npm-snapshots/"
}
Next, I created .npmrc file with following content:
registry=https://my.nexus.com/repository/npm-public/
_auth=RVhBTVBMRQ==
And with this setup I can publish project with no problem. However, what bothers me, is that I have my password (which is just base64 encoded) stored in file, that should be commited, but I can't commit it, due to credentials in it.
I have tried to instead login to npm registry and removed the auth line from .npmrc
npm adduser --registry=https://my.nexus.com/repository/npm-snapshots --always-auth
I got response Logged in as myusername on https://my.nexus.com/repository/npm-snapshots.
However, when I try to run npm publish I get:
npm ERR! code E401
npm ERR! Unable to authenticate, need: BASIC realm="Sonatype Nexus Repository Manager"
npm verb exit [ 1, true ]
npm timing npm Completed in 6867ms
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\XXXX\AppData\Roaming\npm-cache\_logs\2019-07-30T19_31_01_598Z-debug.log
Now in my other project (which is using this library), I simply created .npmrc file with content registry=https://nexus.mjamsek.com/repository/npm-public/ and run command npm adduser --registry=https://my.nexus.com/repository/npm-public --always-auth and I was able to download the published package.
However, the publish still won't work and I don't know why.
EDIT 31.7.2019: On my list of active realms I also have npm Bearer Token Realm
When you do npm login or npm adduser the NPM client creates an authentication token that will be used in future request to the registry. Default NXRM configuration allows only Local Authenticating Realm which doesn't recognise NPM's token. Please make sure you have npm Bearer Token Realm active.
You need a trailing slash on the end of the registry URL passed into npm adduser, otherwise npm will chop off the last segment of the URL, and it won't work.
_auth= replaced with output of btoa('username:userpassword') and it worked for me.
I did use this btoa from chrome as below.
I encountered this problem today, my solution was to delete all registry entry from my npmrc file:
registry=https://my.nexus.com/repository/npm-snapshots/
Idealy delete anything superfluous, back it up before-hand, in my case my file contained only:
strict-ssl=false
Then you can
npm login --registry=https://my.nexus.com/repository/npm-public/ again.
If that's not working, you also bypass npm login with curl, look at this life saving post.
Make sure the _auth token is correct. In my case I changed my system credentials and forgot to generate new _auth token. I was getting the exact same error i.e.
"npm ERR! code E401
npm ERR! Unable to authenticate, need: BASIC realm="Sonatype Nexus Repository Manager"
once i fixed it, the issue was resolved.
For those who are looking for the command to generate _auth. It is:
btoa('username:userpassword')
I had same problem, my solution was to delete my global .npmrc file, and after login npm login.
I had ended with three versions of node on my machine. It turned out that the ones i installed later had their own local .npmrc files in the node_modules folders. They didn't use the global .npmrc even after i removed the local one so i had to copy it.
I was struggling about this problem last two days, finally the solution was to delete .npmrc file from root (user) directory.
When npm tried to login, it used the creds inside this file and ignore your pass login.
I've had a similar issue. I also have our credentials stored in an npmrc file in my user directory. When set up with node16/npm7, I would receive the error
npm ERR! code ENEEDAUTH
npm ERR! need auth This command requires you to be logged in.
npm ERR! need auth You need to authorize this machine using `npm adduser`
If I use nvm to downgrade to node12/npm6, it works. I'd prefer a working solution without downgrading, but for now it lets me move on.
UPDATE:
We finally figured it out (a while ago, but I forgot about this answer). In our .npmrc files in our user directories, we needed to add/change our authorization config entry.
Before:
_auth={base64 encoded username:password}
After:
//{path to private repository}:_auth={base64 encoded username:password}
Just enable anonymous access in the nexus dashboard, it will pull from your private registry.

NPM install resulting in 401 Unauthorized for private repo

I have the following line in my dependencies in package.json:
"log": "https://git.mydomain.com/myproject/myrepo/repository/archive.tar.gz?ref=0.1.0",
I get the following:
km#Karls-MBP ~/dev/vertica (km/ref) $ npm install
npm ERR! code E401
npm ERR! 404 401 Unauthorized: log#https://git.mydomain.com/myproject/myrepo/repository/archive.tar.gz?ref=0.5.0
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/km/.npm/_logs/2018-02-16T08_49_38_669Y-debug.log
I don't know if the issue is GitLab (where the repo exists) or NPM.
Node v8.9.4
NPM v5.6.0
Remove .npmrc from the Home Directory, it should be able to work. I did the same and it works for me.
My user directory .npmrc file had a stale authtoken as below.
//registry.npmjs.org/:_authToken=3615fa68-123a-4d72-b99a-772b5b1edc48
By removing this line, the npm installation works fine and no longer throws an authentication error.
You need to add user to npm registery
>> npm whoami [ it will return not authorized ]
To add new user follow below steps :-
>> npm adduser (then enter your name and complex password and your email)
>> npm whoami (return your registered name)
I got the same error but the reason in my case was different than the above answers:
I discovered that the package-lock.json had some of the packages resolved to a private url instead of the typical public npm urls, so deleting the npm lock file and running npm install again solved it
But if this is the case, you need to check with the team still why this private url resolution happened instead of the normal one
I got this when I used --prefer-offline
- npm ci --cache .npm --prefer-offline --unsafe-perm --no-optional
Removing that option fixed it.
In my case I have to change the content of .npmrc file to package-lock=false.
Now it works fine!
removing the .npmrc from the root directory worked for me
removing the .npmrc from the root directory worked perfectly for me as well
I noticed this error for a public github repo. Removed the entry always-auth = true and was able to proceed.

npm "failed to parse json"

When I'm trying to install express with npm I always get the following error:
Failed to parse json
No data, empty input at 1:1
File: /root/.npm/inherits/2.0.1/package/package.json
Failed to parse package.json data.
package.json must be actual JSON, not just JavaScript.
This is not a bug in npm.
Tell the package author to fix their package.json file. JSON.parse
What am I doing wrong?
sudo npm install -g express
OS is Ubuntu 12.04 (precise) armhf
Thanks to Jivings from this comment:
npm cache clean
solved the problem.
I had the same problem but "npm cache clean" didnt resolve it for me. I had to go back to my package.json and realize i had comma where it shouldn't i suppose as shown below:
},
"devDependencies": {
"axios": "^0.15.3",
"bootstrap-sass": "^3.3.7",
"cross-env": "^3.2.4",
"jquery": "^3.1.1",
"laravel-mix": "0.*",
"lodash": "^4.17.4",
"vue": "^2.1.10",
}
after the "vue..." so I deleted that and every went back to normal. So it is worth checking the package.json file first before running npm cache clean
Mostly, this error is due to a syntax error in package.json file.
In my case, the opening curly brace for dependencies object in package.json was missing:-
Code--------------------------------
{
"name": "psrxjs",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies":
"rxjs": "^5.4.3"
}
}
In Laravel project:
Delete 'node_modules' folder;
npm cache clean
npm update
I solved the issue using below steps:
Delete node_modules folder
Delete package-lock.json file
Run npm install
Run npm start
I also got the same error message while run npm install, first run npm package.json to check errors in package.json file, if not then run npm cache clean
You could get this error from not doing npm init.
I faced this problem several times before I got used to using NPM. Most off the time it was because I failed to use npm init before npm install
For me the issue was fixed by changing the name of the package
from
"name": "portfolio"
to
"name": "portfolio2"
I experienced a similar issue today after updating Node on Windows 10. My local build tasks started failing and upon investigation I saw all these errors in my dependency package.json files. None of them were valid JSON anymore and I was seeing messages like:
npm WARN Failed to parse json
npm WARN Unexpected token '\u0019' at 1:1
npm WARN ������2�����bE�;���1L �\5�e���k2?��,?;��쏏a��(T��w��+I��/�6�P} ��i�|e�
npm WARN ^
in my console.
This story has a happy ending as it turns out that new Node doesn't play nice with old NPM and updating NPM to version 5 solved the problem. Hope this helps other folks who may experience this variation on this issue.
The following bash script fixes the problem automatically
#!/usr/bin/env bash
echo -e '#!/usr/bin/env bash' > npm_install.sh
cat npm-debug.log | grep 'error File:' | sed -n 's:.*error File\: \(.*\):echo "Removing \1"\nrm -f \1\necho "Cleaning npm cache"\nnpm cache clean\necho "Reinstalling npm"\nnpm install\n./npm_reinstall.sh:p' >> npm_install.sh
chmod +x npm_install.sh
./npm_install.sh
It should be saved to npm_reinstall.sh
and granted execution permissions using
chmod +x npm_reinstall.sh
The script is preforming the following tasks:
Looking for an error File : in npm-debug.log using grep
Using sed to generate the fix commands 3-5 only if there are errors
Removing the empty file rm -f /1 = file path from the first group in regular expression .*error File: (.*)
Cleaning npm cache npm cache clean
Reinstalling npm npm install
Running ./npm_reinstall.sh recursively till no errors are found
More information about npm install can be found at npm-install command documentation
In my case
Missing a comma somewhere in a package.json Check your package.json file.
After that sudo npm install
or
To clean the cache memory.
sudo npm cache clean
In addition to Pank's answer, if you encounter this kind of error
npm ERR! code EJSONPARSE
npm ERR! JSON.parse Failed to parse json
npm ERR! JSON.parse Unexpected token } in JSON at position 550 while parsing near '...eact": "^7.12.4",
npm ERR! JSON.parse },
npm ERR! JSON.parse "dependencies":...'
npm ERR! JSON.parse Failed to parse package.json data.
npm ERR! JSON.parse package.json must be actual JSON, not just JavaScript.
You need to make sure your package.json is a valid json, not a javascript.
Please check with unused white spaces inside package.json file, it might cause by extra white spaces.
I think you may be did some change in package.json and that is not valid
Delete node_modules
Delete package.json
Create a new NPM package with
npm init
install all of your package once again
npm install express
For those of you who are new to this like me, I forgot to initialize my JSON package with the npm init command.
remove any unnecessary comments, the error you referred occurs usually due to the syntax error. Or if this won't help, try to clean the cache by "npm cache clean".
1.Basically it comes for wrong placement of comma so remove comma at wrong position(esp error occurs for placing comma(,) before closing flower brace('}') in package.json so look into it. This is one solution
Run
sudo npm cache clean
sudo chown -R 1000:1000 "...path/.npm"
Don't forget to edit your package.json, escpeially the dependencies.
For example, one of my chatting room projects needs the following content in package.json:
{
"name":"chatrooms",
"version":"0.0.1",
"description":"Minimalist multi-room chat server",
"dependencies":{
"socket.io":"~0.9.6",
"mime":"~1.2.7"
}
}
Try to open your txt editor and select "plain text" for the package.json then re-save. Sometimes issue is overlooked and simple things are holding the answer.

Resources