Le concept d’”auth” regroupe à la fois l’authentification (autthentication en anglais) et
l’autorisation (authorization en anglais), qui sont des besoins classiques lorsque l’on construit
une application web. L’authentification signifie vérifier que l’utilisateur ou l’utilisatrice est
bien la personne qu’elle prétend être grâce aux identifiants fournis. L’autorisation signifie
déterminer quelles actions une personne est autorisée à faire.
Sessions vs tokens
Après que la personne a fourni ses identifiants comme un nom et un mot de passe, nous souhaitons les
l’autoriser à utiliser l’application sans qu’elle ait de nouveau besoin de fournir ses identifiants
pour les requêtes futures. Les utilisateurs et utilisatrices sont en généralement authentifiées pour
les requêtes suivantes avec soit un identifiant de session, soit avec un token signé tel qu’un JSON
Web Token (JWT).
Les IDs de sessions sont en général stockés dans une base de données. Ils peuvent être immédiatement
révoqués, mais nécessitent d’interroger la base de données à chaque requête.
À l’inverse, les JWT ne sont généralement pas vérifiés en rapport à une base de données, ce qui
implique qu’ils ne peuvent pas être immédiatement révoqués. L’avantage de cette méthode est une
meilleure latence et une charge réduite sur votre base de données.
Points d’intégrations
Les cookies peuvent être vérifiés dans le hook handle. Si
les identifiants d’utilisateur ou utilisatrice correspondent à une entrée dans la base de données,
les informations d’utilisateur peuvent être stockées dans le champ
locals.
The handle hook runs every time the SvelteKit server receives a request and
determines the response.
It receives an event object representing the request and a function called resolve, which renders the route and generates a Response.
This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example).
The handle hook runs every time the SvelteKit server receives a request and
determines the response.
It receives an event object representing the request and a function called resolve, which renders the route and generates a Response.
This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example).
Vous pouvez ensuite utiliser getRequestEvent pour lire
locals.user et vérifier si l’utilisateur ou l’utilisatrice est authentifiée. Cette vérification
peut être faite dans un utilitaire partagé, puis réutilisée dans chaque fonction load, comme
montré dans cet exemple.
Faites toujours les vérifications dans les fichiers +page.server.js plutôt que dans les
fichiers +layout.server.js — voir la section implications pour
l’authentification.
Protéger plusieurs routes
Pour protéger vos routes privées, ajoutez dans votre hook handle un gardien d’authentification qui
vérifie dans une liste de routes publiques autorisées :
Redirect a request. When called during request handling, SvelteKit will return a redirect response.
Make sure you're not catching the thrown redirect, which would prevent SvelteKit from handling it.
Most common status codes:
303 See Other: redirect as a GET request (often used after a form POST request)
307 Temporary Redirect: redirect will keep the request method
308 Permanent Redirect: redirect will keep the request method, SEO will be transferred to the new page
To redirect to an external URL, you must pass { external: true } to allow any external URL except javascript: URLs, or { external: [...] } with an allowlist of permitted origins.
{import('./public.js').Redirect} This error instructs SvelteKit to redirect to the specified location.
{Error} If the provided status is invalid, the location cannot be used as a header value, or the location is an external URL without permission.
The ID of the current route - e.g. for src/routes/blog/[slug], it would be /blog/[slug]. It is null when no route is matched.
Inside query functions (including query.batch and query.live), accessing this property throws an error.
Pass values from the page as arguments to the query instead. Inside form and command functions it relates to the page
the remote function was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use it
to determine whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated.
Redirect a request. When called during request handling, SvelteKit will return a redirect response.
Make sure you're not catching the thrown redirect, which would prevent SvelteKit from handling it.
Most common status codes:
303 See Other: redirect as a GET request (often used after a form POST request)
307 Temporary Redirect: redirect will keep the request method
308 Permanent Redirect: redirect will keep the request method, SEO will be transferred to the new page
To redirect to an external URL, you must pass { external: true } to allow any external URL except javascript: URLs, or { external: [...] } with an allowlist of permitted origins.
{import('./public.js').Redirect} This error instructs SvelteKit to redirect to the specified location.
{Error} If the provided status is invalid, the location cannot be used as a header value, or the location is an external URL without permission.
Redirect a request. When called during request handling, SvelteKit will return a redirect response.
Make sure you're not catching the thrown redirect, which would prevent SvelteKit from handling it.
Most common status codes:
303 See Other: redirect as a GET request (often used after a form POST request)
307 Temporary Redirect: redirect will keep the request method
308 Permanent Redirect: redirect will keep the request method, SEO will be transferred to the new page
To redirect to an external URL, you must pass { external: true } to allow any external URL except javascript: URLs, or { external: [...] } with an allowlist of permitted origins.
{import('./public.js').Redirect} This error instructs SvelteKit to redirect to the specified location.
{Error} If the provided status is invalid, the location cannot be used as a header value, or the location is an external URL without permission.
The handle hook runs every time the SvelteKit server receives a request and
determines the response.
It receives an event object representing the request and a function called resolve, which renders the route and generates a Response.
This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example).
The handle hook runs every time the SvelteKit server receives a request and
determines the response.
It receives an event object representing the request and a function called resolve, which renders the route and generates a Response.
This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example).
The ID of the current route - e.g. for src/routes/blog/[slug], it would be /blog/[slug]. It is null when no route is matched.
Inside query functions (including query.batch and query.live), accessing this property throws an error.
Pass values from the page as arguments to the query instead. Inside form and command functions it relates to the page
the remote function was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use it
to determine whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated.
Redirect a request. When called during request handling, SvelteKit will return a redirect response.
Make sure you're not catching the thrown redirect, which would prevent SvelteKit from handling it.
Most common status codes:
303 See Other: redirect as a GET request (often used after a form POST request)
307 Temporary Redirect: redirect will keep the request method
308 Permanent Redirect: redirect will keep the request method, SEO will be transferred to the new page
To redirect to an external URL, you must pass { external: true } to allow any external URL except javascript: URLs, or { external: [...] } with an allowlist of permitted origins.
{import('./public.js').Redirect} This error instructs SvelteKit to redirect to the specified location.
{Error} If the provided status is invalid, the location cannot be used as a header value, or the location is an external URL without permission.
Lorsque c’est possible, vous devriez faire utiliser event.route.id plutôt que
event.url.pathname car event.route.id est le nom réel de la route que SvelteKit a fait
correspondre, et représente donc le contenu qui sera servi si la requête est autorisée à progresser.
Les vérifications simples de chaînes de caractères sur le chemin de l’URL peuvent amener toutes
sortes de problèmes — par exemple, le chemin d’URL peut être encodé, de
sorte qu’une vérification telle que event.url.pathname.startsWith('/admin') peut être contournée
avec son équivalent encodé /%61dmin. Si vous devez absolument utiliser une partie brute de l’URL
pour faire votre vérification, assurez-vous d’utiliser un décodage approprié et écrivez des tests
associés.
Les pages pré-rendues et les assets statiques sont servis sans invoquer handle, et ne
peuvent donc pas être protégés de cette manière.
Si vous souhaitez implémenter votre propre système d’authentification, le livre Pilcrow’s Auth
Book fournit une référence pour mettre en place une authentification
d’application web basée sur des tokens de session.
Il existe également un exemple
simple de comment implémenter
ceci de manière générale.