A simple command line to get your 2FA token or password from Bitwarden into your clipboard
On a normal day of work, I need to get my 2FA token multiple times due to a SSO configuration, and it was a pain to open the browser, click my password manager icon, search for SSO and then copy the token.
Then, some time ago, when I was using LastPass as my password provider, they changed the free plan to be used by a single device, which made me move to another provider or pay for a paid plan in LastPass. After realizing how painfull it was to get my 2FA token everytime, I decided to move to a manager with CLI support, that’s when I signed up for Bitwarden’s paid plan ($10/year).
With it’s CLI, it’s very straightforward to retrieve a 2FA token from CLI
bw get totp <query>
I just needed to setup a secure way to store my session, so I can get my tokens without being asked for my master password everytime. After a bw login
, you can run bw unlock
to unlock your vault. After unlock
, you will see something like the print below.
By passing --raw
to bw unlock
, the command will output only the session, which we can save to a file that our terminal will load everytime. This way we will save our session once, and then CLI will use it to query our vault.
echo "export BW_SESSION=$(bw unlock --raw)" >> ~/.zprofile && source ~/.zprofile
Please note that the session returned by the unlock command is meant to be private, because it allows access to your entire vault, which means ALL passwords and 2FA tokens
Then, with our session configured, it’s time to create the functions
Note that the file contains 3 variables to distinguish 3 environments: Linux, MacOS and WSL. This is an optional config that I use, but you can remove then and keep only the OS you use
Then, after loading .zshrc
into the terminal (source
it or restart terminal app), I can simply 2fa auth0
or password github
to copy them to my clipboard.
If you don’t use zsh
, I think this file might work with bash
too, just change .zshrc
to .bashrc
and .zprofile
to .profile
.
I need to say that this will work only if your query returns a single result from Bitwarden’s vault. If your query returns more than 1 result, this error will show up.