mirror of
https://github.com/fastapi/fastapi.git
synced 2026-04-27 18:31:31 -04:00
📝 Refactor docs, "Tutorial - User Guide" and "Advanced User Guide" (#887)
This commit is contained in:
committed by
GitHub
parent
a41a729682
commit
22982287ff
@@ -48,7 +48,7 @@ You will see something like this:
|
||||
!!! check "Authorize button!"
|
||||
You already have a shinny new "Authorize" button.
|
||||
|
||||
And your path operation has a little lock in the top-right corner that you can click.
|
||||
And your *path operation* has a little lock in the top-right corner that you can click.
|
||||
|
||||
And if you click it, you have a little authorization form to type a `username` and `password` (and other optional fields):
|
||||
|
||||
@@ -112,7 +112,7 @@ In this example we are going to use **OAuth2**, with the **Password** flow, usin
|
||||
{!./src/security/tutorial001.py!}
|
||||
```
|
||||
|
||||
It doesn't create that endpoint / path operation, but declares that that URL is the one that the client should use to get the token. That information is used in OpenAPI, and then in the interactive API documentation systems.
|
||||
It doesn't create that endpoint / *path operation*, but declares that that URL is the one that the client should use to get the token. That information is used in OpenAPI, and then in the interactive API documentation systems.
|
||||
|
||||
!!! info
|
||||
If you are a very strict "Pythonista" you might dislike the style of the parameter name `tokenUrl` instead of `token_url`.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
In the previous chapter the security system (which is based on the dependency injection system) was giving the path operation function a `token` as a `str`:
|
||||
In the previous chapter the security system (which is based on the dependency injection system) was giving the *path operation function* a `token` as a `str`:
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!./src/security/tutorial001.py!}
|
||||
@@ -26,7 +26,7 @@ Remember that dependencies can have sub-dependencies?
|
||||
|
||||
`get_current_user` will have a dependency with the same `oauth2_scheme` we created before.
|
||||
|
||||
The same as we were doing before in the path operation directly, our new dependency `get_current_user` will receive a `token` as a `str` from the sub-dependency `oauth2_scheme`:
|
||||
The same as we were doing before in the *path operation* directly, our new dependency `get_current_user` will receive a `token` as a `str` from the sub-dependency `oauth2_scheme`:
|
||||
|
||||
```Python hl_lines="25"
|
||||
{!./src/security/tutorial002.py!}
|
||||
@@ -42,7 +42,7 @@ The same as we were doing before in the path operation directly, our new depende
|
||||
|
||||
## Inject the current user
|
||||
|
||||
So now we can use the same `Depends` with our `get_current_user` in the path operation:
|
||||
So now we can use the same `Depends` with our `get_current_user` in the *path operation*:
|
||||
|
||||
```Python hl_lines="31"
|
||||
{!./src/security/tutorial002.py!}
|
||||
@@ -65,7 +65,7 @@ This will help us inside of the function with all the completion and type checks
|
||||
|
||||
## Other models
|
||||
|
||||
You can now get the current user directly in the path operation functions and deal with the security mechanisms at the **Dependency Injection** level, using `Depends`.
|
||||
You can now get the current user directly in the *path operation functions* and deal with the security mechanisms at the **Dependency Injection** level, using `Depends`.
|
||||
|
||||
And you can use any model or data for the security requirements (in this case, a Pydantic model `User`).
|
||||
|
||||
@@ -82,7 +82,7 @@ Just use any kind of model, any kind of class, any kind of database that you nee
|
||||
|
||||
## Code size
|
||||
|
||||
This example might seem verbose. Have in mind that we are mixing security, data models utility functions and path operations in the same file.
|
||||
This example might seem verbose. Have in mind that we are mixing security, data models utility functions and *path operations* in the same file.
|
||||
|
||||
But here's the key point.
|
||||
|
||||
@@ -90,11 +90,11 @@ The security and dependency injection stuff is written once.
|
||||
|
||||
And you can make it as complex as you want. And still, have it written only once, in a single place. With all the flexibility.
|
||||
|
||||
But you can have thousands of endpoints (path operations) using the same security system.
|
||||
But you can have thousands of endpoints (*path operations*) using the same security system.
|
||||
|
||||
And all of them (or any portion of them that you want) can take the advantage of re-using these dependencies or any other dependencies you create.
|
||||
|
||||
And all these thousands of path operations can be as small as 3 lines:
|
||||
And all these thousands of *path operations* can be as small as 3 lines:
|
||||
|
||||
```Python hl_lines="30 31 32"
|
||||
{!./src/security/tutorial002.py!}
|
||||
@@ -102,10 +102,10 @@ And all these thousands of path operations can be as small as 3 lines:
|
||||
|
||||
## Recap
|
||||
|
||||
You can now get the current user directly in your path operation function.
|
||||
You can now get the current user directly in your *path operation function*.
|
||||
|
||||
We are already halfway there.
|
||||
|
||||
We just need to add a path operation for the user/client to actually send the `username` and `password`.
|
||||
We just need to add a *path operation* for the user/client to actually send the `username` and `password`.
|
||||
|
||||
That comes next.
|
||||
That comes next.
|
||||
|
||||
@@ -1,105 +0,0 @@
|
||||
For the simplest cases, you can use HTTP Basic Auth.
|
||||
|
||||
In HTTP Basic Auth, the application expects a header that contains a username and a password.
|
||||
|
||||
If it doesn't receive it, it returns an HTTP 401 "Unauthorized" error.
|
||||
|
||||
And returns a header `WWW-Authenticate` with a value of `Basic`, and an optional `realm` parameter.
|
||||
|
||||
That tells the browser to show the integrated prompt for a username and password.
|
||||
|
||||
Then, when you type that username and password, the browser sends them in the header automatically.
|
||||
|
||||
## Simple HTTP Basic Auth
|
||||
|
||||
* Import `HTTPBasic` and `HTTPBasicCredentials`.
|
||||
* Create a "`security` scheme" using `HTTPBasic`.
|
||||
* Use that `security` with a dependency in your *path operation*.
|
||||
* It returns an object of type `HTTPBasicCredentials`:
|
||||
* It contains the `username` and `password` sent.
|
||||
|
||||
```Python hl_lines="2 6 10"
|
||||
{!./src/security/tutorial006.py!}
|
||||
```
|
||||
|
||||
When you try to open the URL for the first time (or click the "Execute" button in the docs) the browser will ask you for your username and password:
|
||||
|
||||
<img src="/img/tutorial/security/image12.png">
|
||||
|
||||
## Check the username
|
||||
|
||||
Here's a more complete example.
|
||||
|
||||
Use a dependency to check if the username and password are correct.
|
||||
|
||||
For this, use the Python standard module <a href="https://docs.python.org/3/library/secrets.html" class="external-link" target="_blank">`secrets`</a> to check the username and password:
|
||||
|
||||
```Python hl_lines="1 13 14 15"
|
||||
{!./src/security/tutorial007.py!}
|
||||
```
|
||||
|
||||
This will ensure that `credentials.username` is `"stanleyjobson"`, and that `credentials.password` is `"swordfish"`. This would be similar to:
|
||||
|
||||
```Python
|
||||
if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"):
|
||||
# Return some error
|
||||
...
|
||||
```
|
||||
|
||||
But by using the `secrets.compare_digest()` it will be secure against a type of attacks called "timing attacks".
|
||||
|
||||
### Timing Attacks
|
||||
|
||||
But what's a "timing attack"?
|
||||
|
||||
Let's imagine an attacker is trying to guess the username and password.
|
||||
|
||||
And that attacker sends a request with a username `johndoe` and a password `love123`.
|
||||
|
||||
Then the Python code in your application would be equivalent to something like:
|
||||
|
||||
```Python
|
||||
if "johndoe" == "stanleyjobson" and "love123" == "swordfish":
|
||||
...
|
||||
```
|
||||
|
||||
But right at the moment Python compares the first `j` in `johndoe` to the first `s` in `stanleyjobson`, it will return `False`, because it already knows that those two strings are not the same, thinking that "there's no need to waste more computation comparing the rest of the letters". And your application will say "incorrect user or password".
|
||||
|
||||
But then the attacker tries with username `stanleyjobsox` and password `love123`.
|
||||
|
||||
And your application code does something like:
|
||||
|
||||
```Python
|
||||
if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish":
|
||||
...
|
||||
```
|
||||
|
||||
Python will have to compare the whole `stanleyjobso` in both `stanleyjobsox` and `stanleyjobson` before realizing that both strings are not the same. So it will take some extra microseconds to reply back "incorrect user or password".
|
||||
|
||||
#### The time to answer helps the attacker
|
||||
|
||||
At that point, by noticing that the server took some microseconds longer to send the "incorrect user or password" response, the attacker will know that she/he got _something_ right, some of the initial letters were right.
|
||||
|
||||
And then she/he can try again knowing that it's probably something more similar to `stanleyjobsox` than to `johndoe`.
|
||||
|
||||
#### A "professional" attack
|
||||
|
||||
Of course, the attacker would not try all this by hand, she/he would write a program to do it, possibly with thousands or millions of tests per second. And would get just one extra correct letter at a time.
|
||||
|
||||
But doing that, in some minutes or hours the attacker would have guessed the correct username and password, with the "help" of our application, just using the time taken to answer.
|
||||
|
||||
#### Fix it with `secrets.compare_digest()`
|
||||
|
||||
But in our code we are actually using `secrets.compare_digest()`.
|
||||
|
||||
In short, it will take the same time to compare `stanleyjobsox` to `stanleyjobson` than it takes to compare `johndoe` to `stanleyjobson`. And the same for the password.
|
||||
|
||||
That way, using `secrets.compare_digest()` in your application code, it will be safe against this whole range of security attacks.
|
||||
|
||||
### Return the error
|
||||
|
||||
After detecting that the credentials are incorrect, return an `HTTPException` with a status code 401 (the same returned when no credentials are provided) and add the header `WWW-Authenticate` to make the browser show the login prompt again:
|
||||
|
||||
```Python hl_lines="16 17 18 19 20"
|
||||
{!./src/security/tutorial007.py!}
|
||||
```
|
||||
@@ -18,9 +18,9 @@ It is not encrypted, so, anyone could recover the information from the contents.
|
||||
|
||||
But it's signed. So, when you receive a token that you emitted, you can verify that you actually emitted it.
|
||||
|
||||
That way, you can create a token with an expiration of, let's say, 1 week, and then, after a week, when the user comes back with the token, you know he's still signed into your system.
|
||||
That way, you can create a token with an expiration of, let's say, 1 week. And then when the user comes back the next day with the token, you know she/he is still signed into your system.
|
||||
|
||||
And after a week, the token will be expired. And if the user (or a third party) tried to modify the token to change the expiration, you would be able to discover it, because the signatures would not match.
|
||||
And after a week, the token will be expired and the user will not be authorized and will have to sign in again to get a new token. And if the user (or a third party) tried to modify the token to change the expiration, you would be able to discover it, because the signatures would not match.
|
||||
|
||||
If you want to play with JWT tokens and see how they work, check <a href="https://jwt.io/" class="external-link" target="_blank">https://jwt.io</a>.
|
||||
|
||||
@@ -131,7 +131,7 @@ If the token is invalid, return an HTTP error right away.
|
||||
{!./src/security/tutorial004.py!}
|
||||
```
|
||||
|
||||
## Update the `/token` path operation
|
||||
## Update the `/token` *path operation*
|
||||
|
||||
Create a `timedelta` with the expiration time of the token.
|
||||
|
||||
@@ -211,7 +211,7 @@ You can use them to add a specific set of permissions to a JWT token.
|
||||
|
||||
Then you can give this token to a user directly or a third party, to interact with your API with a set of restrictions.
|
||||
|
||||
You can learn how to use them and how they are integrated into **FastAPI** in the next chapter.
|
||||
You can learn how to use them and how they are integrated into **FastAPI** later in the **Advanced User Guide**.
|
||||
|
||||
## Recap
|
||||
|
||||
@@ -229,10 +229,8 @@ It gives you all the flexibility to choose the ones that fit your project the be
|
||||
|
||||
And you can use directly many well maintained and widely used packages like `passlib` and `pyjwt`, because **FastAPI** doesn't require any complex mechanisms to integrate external packages.
|
||||
|
||||
But it provides you the tools to simplify the process as much as possible without compromising flexibility, robustness or security.
|
||||
But it provides you the tools to simplify the process as much as possible without compromising flexibility, robustness, or security.
|
||||
|
||||
And you can use and implement secure, standard protocols, like OAuth2 in a relatively simple way.
|
||||
|
||||
In the next (optional) section you can see how to extend this even further, using OAuth2 "scopes", for a more fine-grained permission system, following these same standards.
|
||||
|
||||
OAuth2 with scopes (explained in the next section) is the mechanism used by many big authentication providers, like Facebook, Google, GitHub, Microsoft, Twitter, etc.
|
||||
You can learn more in the **Advanced User Guide** about how to use OAuth2 "scopes", for a more fine-grained permission system, following these same standards. OAuth2 with scopes is the mechanism used by many big authentication providers, like Facebook, Google, GitHub, Microsoft, Twitter, etc. to authorize third party applications to interact with their APIs on behalf of their users.
|
||||
|
||||
@@ -1,250 +0,0 @@
|
||||
You can use OAuth2 scopes directly with **FastAPI**, they are integrated to work seamlessly.
|
||||
|
||||
This would allow you to have a more fine-grained permission system, following the OAuth2 standard, integrated into your OpenAPI application (and the API docs).
|
||||
|
||||
OAuth2 with scopes is the mechanism used by many big authentication providers, like Facebook, Google, GitHub, Microsoft, Twitter, etc. They use it to provide specific permissions to users and applications.
|
||||
|
||||
Every time you "log in with" Facebook, Google, GitHub, Microsoft, Twitter, that application is using OAuth2 with scopes.
|
||||
|
||||
In this section you will see how to manage authentication and authorization with the same OAuth2 with scopes in your **FastAPI** application.
|
||||
|
||||
!!! warning
|
||||
This is a more or less advanced section. If you are just starting, you can skip it.
|
||||
|
||||
You don't necessarily need OAuth2 scopes, and you can handle authentication and authorization however you want.
|
||||
|
||||
But OAuth2 with scopes can be nicely integrated into your API (with OpenAPI) and your API docs.
|
||||
|
||||
Nevertheless, you still enforce those scopes, or any other security/authorization requirement, however you need, in your code.
|
||||
|
||||
In many cases, OAuth2 with scopes can be an overkill.
|
||||
|
||||
But if you know you need it, or you are curious, keep reading.
|
||||
|
||||
## OAuth2 scopes and OpenAPI
|
||||
|
||||
The OAuth2 specification defines "scopes" as a list of strings separated by spaces.
|
||||
|
||||
The content of each of these strings can have any format, but should not contain spaces.
|
||||
|
||||
These scopes represent "permissions".
|
||||
|
||||
In OpenAPI (e.g. the API docs), you can define "security schemes", the same as you saw in the previous sections.
|
||||
|
||||
When one of these security schemes uses OAuth2, you can also declare and use scopes.
|
||||
|
||||
## Global view
|
||||
|
||||
First, let's quickly see the parts that change from the previous section about OAuth2 and JWT. Now using OAuth2 scopes:
|
||||
|
||||
```Python hl_lines="2 5 9 13 48 66 107 109 110 111 112 113 114 115 116 117 123 124 125 126 130 131 132 133 134 135 136 141 155"
|
||||
{!./src/security/tutorial005.py!}
|
||||
```
|
||||
|
||||
Now let's review those changes step by step.
|
||||
|
||||
## OAuth2 Security scheme
|
||||
|
||||
The first change is that now we are declaring the OAuth2 security scheme with two available scopes, `me` and `items`.
|
||||
|
||||
The `scopes` parameter receives a `dict` with each scope as a key and the description as the value:
|
||||
|
||||
```Python hl_lines="64 65 66 67"
|
||||
{!./src/security/tutorial005.py!}
|
||||
```
|
||||
|
||||
Because we are now declaring those scopes, they will show up in the API docs when you log-in/authorize.
|
||||
|
||||
And you will be able to select which scopes you want to give access to: `me` and `items`.
|
||||
|
||||
This is the same mechanism used when you give permissions while logging in with Facebook, Google, GitHub, etc:
|
||||
|
||||
<img src="/img/tutorial/security/image11.png">
|
||||
|
||||
## JWT token with scopes
|
||||
|
||||
Now, modify the token *path operation* to return the scopes requested.
|
||||
|
||||
We are still using the same `OAuth2PasswordRequestForm`. It includes a property `scopes` with a `list` of `str`, with each scope it received in the request.
|
||||
|
||||
And we return the scopes as part of the JWT token.
|
||||
|
||||
!!! danger
|
||||
For simplicity, here we are just adding the scopes received directly to the token.
|
||||
|
||||
But in your application, for security, you should make sure you only add the scopes that the user is actually able to have, or the ones you have predefined.
|
||||
|
||||
```Python hl_lines="156"
|
||||
{!./src/security/tutorial005.py!}
|
||||
```
|
||||
|
||||
## Declare scopes in *path operations* and dependencies
|
||||
|
||||
Now we declare that the *path operation* for `/users/me/items/` requires the scope `items`.
|
||||
|
||||
For this, we import and use `Security` from `fastapi`.
|
||||
|
||||
You can use `Security` to declare dependencies (just like `Depends`), but `Security` also receives a parameter `scopes` with a list of scopes (strings).
|
||||
|
||||
In this case, we pass a dependency function `get_current_active_user` to `Security` (the same way we would do with `Depends`).
|
||||
|
||||
But we also pass a `list` of scopes, in this case with just one scope: `items` (it could have more).
|
||||
|
||||
And the dependency function `get_current_active_user` can also declare sub-dependencies, not only with `Depends` but also with `Security`. Declaring its own sub-dependency function (`get_current_user`), and more scope requirements.
|
||||
|
||||
In this case, it requires the scope `me` (it could require more than one scope).
|
||||
|
||||
!!! note
|
||||
You don't necessarily need to add different scopes in different places.
|
||||
|
||||
We are doing it here to demonstrate how **FastAPI** handles scopes declared at different levels.
|
||||
|
||||
```Python hl_lines="5 141 168"
|
||||
{!./src/security/tutorial005.py!}
|
||||
```
|
||||
|
||||
!!! info "Technical Details"
|
||||
`Security` is actually a subclass of `Depends`, and it has just one extra parameter that we'll see later.
|
||||
|
||||
But by using `Security` instead of `Depends`, **FastAPI** will know that it can declare security scopes, use them internally, and document the API with OpenAPI.
|
||||
|
||||
But when you import `Query`, `Path`, `Depends`, `Security` and others from `fastapi`, <a href="https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#recap" target="_blank">those are actually functions that return classes of the same name</a>.
|
||||
|
||||
## Use `SecurityScopes`
|
||||
|
||||
Now update the dependency `get_current_user`.
|
||||
|
||||
This is the one used by the dependencies above.
|
||||
|
||||
Here's were we are using the same OAuth2 scheme we created before, declaring it as a dependency: `oauth2_scheme`.
|
||||
|
||||
Because this dependency function doesn't have any scope requirements itself, we can use `Depends` with `oauth2_scheme`, we don't have to use `Security` when we don't need to specify security scopes.
|
||||
|
||||
We also declare a special parameter of type `SecurityScopes`, imported from `fastapi.security`.
|
||||
|
||||
This `SecurityScopes` class is similar to `Request` (`Request` was used to get the request object directly).
|
||||
|
||||
```Python hl_lines="9 107"
|
||||
{!./src/security/tutorial005.py!}
|
||||
```
|
||||
|
||||
## Use the `scopes`
|
||||
|
||||
The parameter `security_scopes` will be of type `SecurityScopes`.
|
||||
|
||||
It will have a property `scopes` with a list containing all the scopes required by itself and all the dependencies that use this as a sub-dependency. That means, all the "dependants"... this might sound confusing, it is explained again later below.
|
||||
|
||||
The `security_scopes` object (of class `SecurityScopes`) also provides a `scope_str` attribute with a single string, containing those scopes separated by spaces (we are going to use it).
|
||||
|
||||
We create an `HTTPException` that we can re-use (`raise`) later at several points.
|
||||
|
||||
In this exception, we include the scopes required (if any) as a string separated by spaces (using `scope_str`). We put that string containing the scopes in in the `WWW-Authenticate` header (this is part of the spec).
|
||||
|
||||
```Python hl_lines="107 109 110 111 112 113 114 115 116 117"
|
||||
{!./src/security/tutorial005.py!}
|
||||
```
|
||||
|
||||
## Verify the `username` and data shape
|
||||
|
||||
We verify that we get a `username`, and extract the scopes.
|
||||
|
||||
And then we validate that data with the Pydantic model (catching the `ValidationError` exception), and if we get an error reading the JWT token or validating the data with Pydantic, we raise the `HTTPException` we created before.
|
||||
|
||||
For that, we update the Pydantic model `TokenData` with a new property `scopes`.
|
||||
|
||||
By validating the data with Pydantic we can make sure that we have, for example, exactly a `list` of `str` with the scopes and a `str` with the `username`.
|
||||
|
||||
Instead of, for example, a `dict`, or something else, as it could break the application at some point later, making it a security risk.
|
||||
|
||||
We also verify that we have a user with that username, and if not, we raise that same exception we created before.
|
||||
|
||||
```Python hl_lines="48 118 119 120 121 122 123 124 125 126 127 128 129"
|
||||
{!./src/security/tutorial005.py!}
|
||||
```
|
||||
|
||||
## Verify the `scopes`
|
||||
|
||||
We now verify that all the scopes required, by this dependency and all the dependants (including *path operations*), are included in the scopes provided in the token received, otherwise raise an `HTTPException`.
|
||||
|
||||
For this, we use `security_scopes.scopes`, that contains a `list` with all these scopes as `str`.
|
||||
|
||||
```Python hl_lines="130 131 132 133 134 135 136"
|
||||
{!./src/security/tutorial005.py!}
|
||||
```
|
||||
|
||||
## Dependency tree and scopes
|
||||
|
||||
Let's review again this dependency tree and the scopes.
|
||||
|
||||
As the `get_current_active_user` dependency has as a sub-dependency on `get_current_user`, the scope `"me"` declared at `get_current_active_user` will be included in the list of required scopes in the `security_scopes.scopes` passed to `get_current_user`.
|
||||
|
||||
The *path operation* itself also declares a scope, `"items"`, so this will also be in the list of `security_scopes.scopes` passed to `get_current_user`.
|
||||
|
||||
Here's how the hierarchy of dependencies and scopes looks like:
|
||||
|
||||
* The *path operation* `read_own_items` has:
|
||||
* Required scopes `["items"]` with the dependency:
|
||||
* `get_current_active_user`:
|
||||
* The dependency function `get_current_active_user` has:
|
||||
* Required scopes `["me"]` with the dependency:
|
||||
* `get_current_user`:
|
||||
* The dependency function `get_current_user` has:
|
||||
* No scopes required by itself.
|
||||
* A dependency using `oauth2_scheme`.
|
||||
* A `security_scopes` parameter of type `SecurityScopes`:
|
||||
* This `security_scopes` parameter has a property `scopes` with a `list` containing all these scopes declared above, so:
|
||||
* `security_scopes.scopes` will contain `["me", "items"]` for the *path operation* `read_own_items`.
|
||||
* `security_scopes.scopes` will contain `["me"]` for the *path operation* `read_users_me`, because it is declared in the dependency `get_current_active_user`.
|
||||
* `security_scopes.scopes` will contain `[]` (nothing) for the *path operation* `read_system_status`, because it didn't declare any `Security` with `scopes`, and its dependency, `get_current_user`, doesn't declare any `scope` either.
|
||||
|
||||
!!! tip
|
||||
The important and "magic" thing here is that `get_current_user` will have a different list of `scopes` to check for each *path operation*.
|
||||
|
||||
All depending on the `scopes` declared in each *path operation* and each dependency in the dependency tree for that specific path operation.
|
||||
|
||||
## More details about `SecurityScopes`
|
||||
|
||||
You can use `SecurityScopes` at any point, and in multiple places, it doesn't have to be at the "root" dependency.
|
||||
|
||||
It will always have the security scopes declared in the current `Security` dependencies and all the dependants for **that specific** *path operation* and **that specific** dependency tree.
|
||||
|
||||
Because the `SecurityScopes` will have all the scopes declared by dependants, you can use it to verify that a token has the required scopes in a central dependency function, and then declare different scope requirements in different *path operations*.
|
||||
|
||||
They will be checked independently for each path operation.
|
||||
|
||||
## Check it
|
||||
|
||||
If you open the API docs, you can authenticate and specify which scopes you want to authorize.
|
||||
|
||||
<img src="/img/tutorial/security/image11.png">
|
||||
|
||||
If you don't select any scope, you will be "authenticated", but when you try to access `/users/me/` or `/users/me/items/` you will get an error saying that you don't have enough permissions. You will still be able to access `/status/`.
|
||||
|
||||
And if you select the scope `me` but not the scope `items`, you will be able to access `/users/me/` but not `/users/me/items/`.
|
||||
|
||||
That's what would happen to a third party application that tried to access one of these *path operations* with a token provided by a user, depending on how many permissions the user gave the application.
|
||||
|
||||
## About third party integrations
|
||||
|
||||
In this example we are using the OAuth2 "password" flow.
|
||||
|
||||
This is appropriate when we are logging in to our own application, probably with our own frontend.
|
||||
|
||||
Because we can trust it to receive the `username` and `password`, as we control it.
|
||||
|
||||
But if you are building an OAuth2 application that others would connect to (i.e., if you are building an authentication provider equivalent to Facebook, Google, GitHub, etc.) you should use one of the other flows.
|
||||
|
||||
The most common is the implicit flow.
|
||||
|
||||
The most secure is the code flow, but is more complex to implement as it requires more steps. As it is more complex, many providers end up suggesting the implicit flow.
|
||||
|
||||
!!! note
|
||||
It's common that each authentication provider names their flows in a different way, to make it part of their brand.
|
||||
|
||||
But in the end, they are implementing the same OAuth2 standard.
|
||||
|
||||
**FastAPI** includes utilities for all these OAuth2 authentication flows in `fastapi.security.oauth2`.
|
||||
|
||||
## `Security` in decorator `dependencies`
|
||||
|
||||
The same way you can define a `list` of <a href="https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/" target="_blank">`Depends` in the decorator's `dependencies` parameter</a>, you could also use `Security` with `scopes` there.
|
||||
@@ -12,7 +12,7 @@ But don't worry, you can show it as you wish to your final users in the frontend
|
||||
|
||||
And your database models can use any other names you want.
|
||||
|
||||
But for the login path operation, we need to use these names to be compatible with the spec (and be able to, for example, use the integrated API documentation system).
|
||||
But for the login *path operation*, we need to use these names to be compatible with the spec (and be able to, for example, use the integrated API documentation system).
|
||||
|
||||
The spec also states that the `username` and `password` must be sent as form data (so, no JSON here).
|
||||
|
||||
@@ -26,14 +26,14 @@ Each "scope" is just a string (without spaces).
|
||||
|
||||
They are normally used to declare specific security permissions, for example:
|
||||
|
||||
* `"users:read"` or `"users:write"` are common examples.
|
||||
* `users:read` or `users:write` are common examples.
|
||||
* `instagram_basic` is used by Facebook / Instagram.
|
||||
* `https://www.googleapis.com/auth/drive` is used by Google.
|
||||
|
||||
!!! info
|
||||
In OAuth2 a "scope" is just a string that declares a specific permission required.
|
||||
|
||||
It doesn't matter if it has other characters like `:`, or if it is a URL.
|
||||
It doesn't matter if it has other characters like `:` or if it is a URL.
|
||||
|
||||
Those details are implementation specific.
|
||||
|
||||
@@ -114,7 +114,7 @@ But you cannot convert from the gibberish back to the password.
|
||||
|
||||
If your database is stolen, the thief won't have your users' plaintext passwords, only the hashes.
|
||||
|
||||
So, the thief won't be able to try to use that password in another system (as many users use the same password everywhere, this would be dangerous).
|
||||
So, the thief won't be able to try to use those same passwords in another system (as many users use the same password everywhere, this would be dangerous).
|
||||
|
||||
```Python hl_lines="79 80 81 82"
|
||||
{!./src/security/tutorial003.py!}
|
||||
@@ -137,7 +137,7 @@ UserInDB(
|
||||
```
|
||||
|
||||
!!! info
|
||||
For a more complete explanation of `**user_dict` check back in <a href="/tutorial/extra-models/#about-user_indict" target="_blank">the documentation for **Extra Models**</a>.
|
||||
For a more complete explanation of `**user_dict` check back in [the documentation for **Extra Models**](../extra-models.md#about-user_indict){.internal-link target=_blank}.
|
||||
|
||||
## Return the token
|
||||
|
||||
|
||||
Reference in New Issue
Block a user