Skip to content

Commit 3d11c57

Browse files
Wauplinstevhliu
andauthored
Login/authentication enhancements (#1895)
* Login enhancements * Apply suggestions from code review Co-authored-by: Steven Liu <59462357+stevhliu@users.noreply.github.com> * example * handle google colab errors * fix contrib test * fix 1 test * fix tetst * fix test --------- Co-authored-by: Steven Liu <59462357+stevhliu@users.noreply.github.com>
1 parent 1932bb0 commit 3d11c57

23 files changed

+270
-152
lines changed

contrib/conftest.py

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
1+
import os
12
import time
23
import uuid
34
from typing import Generator
45

56
import pytest
67

7-
from huggingface_hub import HfFolder, delete_repo
8+
from huggingface_hub import delete_repo
89

910

1011
@pytest.fixture(scope="session")
@@ -20,18 +21,12 @@ def user() -> str:
2021

2122
@pytest.fixture(autouse=True, scope="session")
2223
def login_as_dummy_user(token: str) -> Generator:
23-
"""Login with dummy user token on machine
24-
25-
Once all tests are completed, set back previous token."""
26-
# Remove registered token
27-
old_token = HfFolder().get_token()
28-
HfFolder().save_token(token)
29-
30-
yield # Run all tests
31-
32-
# Set back token once all tests have passed
33-
if old_token is not None:
34-
HfFolder().save_token(old_token)
24+
"""Login with dummy user token."""
25+
# Cannot use `monkeypatch` fixture since we want it to be "session-scoped"
26+
old_token = os.environ["HF_TOKEN"]
27+
os.environ["HF_TOKEN"] = token
28+
yield
29+
os.environ["HF_TOKEN"] = old_token
3530

3631

3732
@pytest.fixture

docs/source/en/guides/cli.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,8 @@ Your token has been saved to /home/wauplin/.cache/huggingface/token
9292
Login successful
9393
```
9494

95+
For more details about authentication, check out [this section](../quick-start#authentication).
96+
9597
## huggingface-cli whoami
9698

9799
If you want to know if you are logged in, you can use `huggingface-cli whoami`. This command doesn't have any options and simply prints your username and the organizations you are a part of on the Hub:

docs/source/en/guides/hf_file_system.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ The same workflow can also be used for [Dask](https://docs.dask.org/en/stable/ho
9797

9898
## Authentication
9999

100-
In many cases, you must be logged in with a Hugging Face account to interact with the Hub. Refer to the [Login](../quick-start#login) section of the documentation to learn more about authentication methods on the Hub.
100+
In many cases, you must be logged in with a Hugging Face account to interact with the Hub. Refer to the [Authentication](../quick-start#authentication) section of the documentation to learn more about authentication methods on the Hub.
101101

102102
It is also possible to login programmatically by passing your `token` as an argument to [`HfFileSystem`]:
103103

docs/source/en/guides/inference.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ code as before, changing only the `model` parameter:
9797

9898
Calls made with the [`InferenceClient`] can be authenticated using a [User Access Token](https://huggingface.co/docs/hub/security-tokens).
9999
By default, it will use the token saved on your machine if you are logged in (check out
100-
[how to login](https://huggingface.co/docs/huggingface_hub/quick-start#login)). If you are not logged in, you can pass
100+
[how to authenticate](https://huggingface.co/docs/huggingface_hub/quick-start#authentication)). If you are not logged in, you can pass
101101
your token as an instance parameter:
102102

103103
```python

docs/source/en/guides/repository.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ explanation page for more details.
2727
</Tip>
2828

2929
If you want to create and manage a repository on the Hub, your machine must be logged in. If you are not, please refer to
30-
[this section](../quick-start#login). In the rest of this guide, we will assume that your machine is logged in.
30+
[this section](../quick-start#authentication). In the rest of this guide, we will assume that your machine is logged in.
3131

3232
## Repo creation and deletion
3333

docs/source/en/guides/upload.md

Lines changed: 1 addition & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -11,31 +11,7 @@ Sharing your files and work is an important aspect of the Hub. The `huggingface_
1111
- with the `commit` context manager.
1212
- with the [`~Repository.push_to_hub`] function.
1313

14-
Whenever you want to upload files to the Hub, you need to log in to your Hugging Face account:
15-
16-
- Log in to your Hugging Face account with the following command:
17-
18-
```bash
19-
huggingface-cli login
20-
# or using an environment variable
21-
huggingface-cli login --token $HUGGINGFACE_TOKEN
22-
```
23-
24-
- Alternatively, you can programmatically login using [`login`] in a notebook or a script:
25-
26-
```python
27-
>>> from huggingface_hub import login
28-
>>> login()
29-
```
30-
31-
If ran in a Jupyter or Colaboratory notebook, [`login`] will launch a widget from
32-
which you can enter your Hugging Face access token. Otherwise, a message will be
33-
prompted in the terminal.
34-
35-
It is also possible to login programmatically without the widget by directly passing
36-
the token to [`login`]. If you do so, be careful when sharing your notebook. It is
37-
best practice to load the token from a secure vault instead of saving it in plain in
38-
your Colaboratory notebook.
14+
Whenever you want to upload files to the Hub, you need to log in to your Hugging Face account. For more details about authentication, check out [this section](../quick-start#authentication).
3915

4016
## Upload a file
4117

docs/source/en/package_reference/environment_variables.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ Defaults to `"$HF_HOME/assets"` (e.g. `"~/.cache/huggingface/assets"` by default
4949
To configure the User Access Token to authenticate to the Hub. If set, this value will
5050
overwrite the token stored on the machine (in `"$HF_HOME/token"`).
5151

52-
See [login reference](../package_reference/login) for more details.
52+
For more details about authentication, check out [this section](../quick-start#authentication).
5353

5454
### HF_HUB_VERBOSITY
5555

docs/source/en/package_reference/hf_api.md

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -109,15 +109,6 @@ Below are the supported values for [`CommitOperation`]:
109109

110110
[[autodoc]] CommitScheduler
111111

112-
## Token helper
113-
114-
`huggingface_hub` stores the authentication information locally so that it may be re-used in subsequent
115-
methods.
116-
117-
It does this using the [`HfFolder`] utility, which saves data at the root of the user.
118-
119-
[[autodoc]] HfFolder
120-
121112
## Search helpers
122113

123114
Some helpers to filter repositories on the Hub are available in the `huggingface_hub` package.

docs/source/en/package_reference/login.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,9 @@ rendered properly in your Markdown viewer.
44

55
# Login and logout
66

7-
The `huggingface_hub` library allows users to programmatically login and logout the
8-
machine to the Hub.
7+
The `huggingface_hub` library allows users to programmatically login and logout the machine to the Hub.
8+
9+
For more details about authentication, check out [this section](../quick-start#authentication).
910

1011
## login
1112

docs/source/en/quick-start.md

Lines changed: 46 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -51,45 +51,75 @@ full-length hash instead of the shorter 7-character commit hash:
5151

5252
For more details and options, see the API reference for [`hf_hub_download`].
5353

54-
## Login
54+
<a id="login"></a> <!-- backward compatible anchor -->
5555

56-
In a lot of cases, you must be logged in with a Hugging Face account to interact with
56+
## Authentication
57+
58+
In a lot of cases, you must be authenticated with a Hugging Face account to interact with
5759
the Hub: download private repos, upload files, create PRs,...
5860
[Create an account](https://huggingface.co/join) if you don't already have one, and then sign in
5961
to get your [User Access Token](https://huggingface.co/docs/hub/security-tokens) from
6062
your [Settings page](https://huggingface.co/settings/tokens). The User Access Token is
6163
used to authenticate your identity to the Hub.
6264

63-
Once you have your User Access Token, run the following command in your terminal:
65+
<Tip>
66+
67+
Tokens can have `read` or `write` permissions. Make sure to have a `write` access token if you want to create or edit a repository. Otherwise, it's best to generate a `read` token to reduce risk in case your token is inadvertently leaked.
68+
69+
</Tip>
70+
71+
### Login command
72+
73+
The easiest way to authenticate is to save the token on your machine. You can do that from the terminal using the [`login`] command:
6474

6575
```bash
6676
huggingface-cli login
67-
# or using an environment variable
68-
huggingface-cli login --token $HUGGINGFACE_TOKEN
6977
```
7078

79+
The command will tell you if you are already logged in and prompt you for your token. The token is then validated and saved in your `HF_HOME` directory (defaults to `~/.cache/huggingface/token`). Any script or library interacting with the Hub will use this token when sending requests.
80+
7181
Alternatively, you can programmatically login using [`login`] in a notebook or a script:
7282

7383
```py
7484
>>> from huggingface_hub import login
7585
>>> login()
7686
```
7787

78-
It is also possible to login programmatically without being prompted to enter your token by directly
79-
passing the token to [`login`] like `login(token="hf_xxx")`. If you do so, be careful when
80-
sharing your source code. It is a best practice to load the token from a secure vault instead
81-
of saving it explicitly in your codebase/notebook.
88+
You can only be logged in to one account at a time. Logging in to a new account will automatically log you out of the previous one. To determine your currently active account, simply run the `huggingface-cli whoami` command.
89+
90+
<Tip warning={true}>
91+
92+
Once logged in, all requests to the Hub - even methods that don't necessarily require authentication - will use your access token by default. If you want to disable the implicit use of your token, you should set `HF_HUB_DISABLE_IMPLICIT_TOKEN=1` as an environment variable (see [reference](../package_reference/environment_variables#hfhubdisableimplicittoken)).
93+
94+
</Tip>
95+
96+
### Environment variable
97+
98+
The environment variable `HF_TOKEN` can also be used to authenticate yourself. This is especially useful in a Space where you can set `HF_TOKEN` as a [Space secret](https://huggingface.co/docs/hub/spaces-overview#managing-secrets).
99+
100+
<Tip>
101+
102+
**NEW:** Google Colaboratory lets you define [private keys](https://twitter.com/GoogleColab/status/1719798406195867814) for your notebooks. Define a `HF_TOKEN` secret to be automatically authenticated!
103+
104+
</Tip>
105+
106+
Authentication via an environment variable or a secret has priority over the token stored on your machine.
107+
108+
### Method parameters
109+
110+
Finally, it is also possible to authenticate by passing your token to any method that accepts `token` as a parameter.
111+
112+
```
113+
from transformers import whoami
114+
115+
user = whoami(token=...)
116+
```
82117

83-
You can be logged in only to 1 account at a time. If you login your machine to a new account, you will get logged out
84-
from the previous. Make sure to always which account you are using with the command `huggingface-cli whoami`.
85-
If you want to handle several accounts in the same script, you can provide your token when calling each method. This
86-
is also useful if you don't want to store any token on your machine.
118+
This is usually discouraged except in an environment where you don't want to store your token permanently or if you need to handle several tokens at once.
87119

88120
<Tip warning={true}>
89121

90-
Once you are logged in, all requests to the Hub -even methods that don't necessarily require authentication- will use your
91-
access token by default. If you want to disable implicit use of your token, you should set the
92-
`HF_HUB_DISABLE_IMPLICIT_TOKEN` environment variable.
122+
Please be careful when passing tokens as a parameter. It is always best practice to load the token from a secure vault instead of hardcoding it in your codebase or notebook. Hardcoded tokens present a major leak risk if you share your code inadvertently.
93123

94124
</Tip>
95125

setup.cfg

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,5 +61,7 @@ max-line-length = 119
6161
# --durations=0 -> print execution time of each test
6262
addopts = -Werror::FutureWarning --log-cli-level=INFO -sv --durations=0
6363
env =
64+
HF_TOKEN=
65+
HUGGING_FACE_HUB_TOKEN=
6466
HUGGINGFACE_CO_STAGING=1
6567
DISABLE_SYMLINKS_IN_WINDOWS_TESTS=1

src/huggingface_hub/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@
6363
"InferenceEndpointType",
6464
],
6565
"_login": [
66+
"get_token",
6667
"interpreter_login",
6768
"login",
6869
"logout",
@@ -406,6 +407,7 @@ def __dir__():
406407
InferenceEndpointType, # noqa: F401
407408
)
408409
from ._login import (
410+
get_token, # noqa: F401
409411
interpreter_login, # noqa: F401
410412
login, # noqa: F401
411413
logout, # noqa: F401

0 commit comments

Comments
 (0)