有些连接到其他服务的 Emacs 软件包需要身份验证,由于反复提供相同的用户名和密码可能会令人烦恼,Emacs 通过 auth-source 库提供了持久化信息。
默认情况下,身份验证信息来自
~/.authinfo
或~/.authinfo.gpg
或~/.netrc
文件。这些文件的语法与 ftp 程序中的 netrc 文件类似,如下所示:
machine mymachine login myloginname password mypassword port myport
Emacs 是通过 auth-source 去实现身份验证的,一般将验证信息 (例如 API Key) 存储在这三个文件中:
而验证信息的格式是:
machine mymachine login myloginname password mypassword port myport
其中:
:host
。:user
。也可以使用 login 和 account 。:port
。一些例子:
machine localhost login spike port sudo password xxxx machine 192.168.100.100 login root port ssh password xxxx machine api.deepseek.com login apikey password xxxx machine api.siliconflow.cn login apikey password xxxx machine openrouter.ai login apikey password xxxx machine openrouter.ai/api login apikey password xxxx
一些插件可能会基于 machine 或者 login 去查找密钥,具体如何设置就需要看插件是如何读取的。
例如 emacs-immersive-translate 是这样读取的:
(defun immersive-translate-api-key (host user) "Lookup api key in the auth source. By default, `immersive-translate-chatgpt-host' is used as HOST and \"apikey\" as USER in Chatgpt backend. \"fanyi-api.baidu.com\" is used as HOST and `immersive-translate-baidu-appid' as USER in Baidu backend." (if-let ((secret (plist-get (car (auth-source-search :host host :user user :require '(:secret))) :secret))) (if (functionp secret) (encode-coding-string (funcall secret) 'utf-8) secret) (user-error "No %s found in the auth source" user)))
immersive-translate-chatgpt.el 中设置 ChatGPT 的密钥:
;; ...其他代码 ("Authorization" . ,(concat "Bearer " (immersive-translate-api-key immersive-translate-chatgpt-host "apikey")))))) ;; ...其他代码
可以看到,emacs-immersive-translate 基于 :host 和 :user 去查找的:
:host
(machine) 是 immersive-translate-chatgpt-host
,默认是 api.openai.com:user
(login) 是 apikey
所以按照默认配置,当你获取到 openai 的 API key 后,要这样配置:
machine api.openai.com login apikey password your_openai_api_key
如果你只是希望配置好 API key 给插件用,你只需要将 API key 按照插件要求定义在 ~/.authinfo 中,就足够了。
如果你想共享 ~/.authinfo,例如分享给特定的人,推送到公开的 git 仓库,同步到云盘,你不想所有人都能看到你的密钥,那你可能需要进一步对文件进行加密。