---
# System prepended metadata

title: npm publish 出現未登入以及 403 (2fa enabled is required to publish)
tags: [FHIR]

---

# npm publish 出現未登入以及 403 (2fa enabled is required to publish)

## 前言

已經有段時間沒有更新 npm 的 package 了，剛好今天更新時，跳出需要重新登入的訊息，登入後，下 `npm publish` 卻又出現 `Two-factor authentication or granular access token with bypass 2fa enabled is required to publish packages.` 的訊息，看了官方的 blog [npm classic tokens revoked, session-based auth and CLI token management now available](https://github.blog/changelog/2025-12-09-npm-classic-tokens-revoked-session-based-auth-and-cli-token-management-now-available/)，才發現原本的方式已經被棄用，需要使用更安全的方式

## 啟用 2FA

- 到 NPM 的官網登入帳號
- 點擊大頭貼 - > Account -> Enable 2FA
![2FA Block](https://hackmd.io/_uploads/H10v1KzmWg.png)


## 重新登入

看到沒有登入的問題，肯定就是先下 `npm login` 重新登入，輸入後，會跳出一段網址，點開後登入即可

## 取得新 token

因為我們需要把 pakcage publish 到 registry 上面去，所以我們需要取得 token 才能 publish

- 進入 npmjs.com/settings/~/tokens 產生
![token page](https://hackmd.io/_uploads/HyF26uMmbe.png)
- 點擊 Generate New Token
- 輸入相關資料後，點擊產生
- 在終端機輸入 `npm token list` 應該就會出現剛剛的 token name 了
![terminal token list](https://hackmd.io/_uploads/B1TVAOzQ-x.png)

## 更改 package 的驗證方式

- 進到需要 publish 的 pakcage 頁面
- 點擊 Settings
![Screenshot showing the admin tab on a package page](https://hackmd.io/_uploads/B1_VlKGXZx.png)
- 更改 Publishing access
![Screenshot showing the require two-factor option for a package](https://hackmd.io/_uploads/HJ_TgYfmZg.png)

1. `Require two-factor authentication or a granular access token with bypass 2fa enabled` (Default)
在此設定下，maintainers 必須在其帳號上啟用 two-factor authentication。若以互動式方式發布 package（使用 npm publish 指令），在執行 publish 時必須回應 2FA prompt。
但 maintainers 也可以建立一個啟用 bypass 2FA 的 granular access token，並使用該 token 進行非互動式（non-interactive）發布。
> This is the default option for all new packages. With this option, maintainers must have two-factor authentication enabled for their account. If they publish a package interactively, using the npm publish command, they will be required to respond to a 2FA prompt when they perform the publish. However, maintainers may also create a granular access token with bypass 2FA enabled and use that for a non-interactive publish.
2. `Require two-factor authentication and disallow tokens` (Recommended) 在此設定下，maintainer 必須在其帳號上啟用 two-factor authentication，且必須以互動式方式進行發布。執行 publish 時，maintainers 必須回應 2FA prompt。
不論 granular access token 是否設定 bypass 2FA，皆不可用於發布 packages。
> With this option, a maintainer must have two-factor authentication enabled for their account, and they must publish interactively. Maintainers will be required to respond to a 2FA prompt when they perform the publish. Granular access tokens cannot be used to publish packages, regardless of their bypass 2FA setting.

可以發現不管哪種方式，現在帳號都必須開啟 2FA 才能 Publish pakcage


