Authentication in Svelte using cookies.pptx

knoldus 24 views 22 slides May 13, 2024
Slide 1
Slide 1 of 22
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22

About This Presentation

Svelte streamlines authentication with cookies, offering a secure and seamless user experience. Effortlessly manage sessions by storing tokens in cookies, ensuring persistent logins. With Svelte's simplicity, implement robust authentication mechanisms, enhancing user security and interaction.


Slide Content

Authentication in Svelte using cookies Alka Vats & Anuj Tomar

Lack of etiquette and manners is a huge turn off.   KnolX Etiquettes Punctuality Join the session 5 minutes prior to the session start time. We start on time and conclude on time! Feedback Make sure to submit a constructive feedback for all sessions as it is very helpful for the presenter. Silent Mode Keep your mobile devices in silent mode, feel free to move out of session in case you need to attend an urgent call. Avoid Disturbance Avoid unwanted chit chat during the session.

Introduction to SvelteKit What are HTTP cookies? Understanding SvelteKit cookies methods Authentication using the parent() function Implementing authentication with SvelteKit Build the UI Authentication endpoints Svelte hooks Securing routes and accessing the session on the client

Introduction to SvelteKit

Introduction to SvelteKit SvelteKit is to Svelte what Next.js is to React.  SvelteKit is a framework for building web applications of all sizes, with a beautiful development experience and flexible file system–based routing. SvelteKit extends Svelte with some functionality that we will use in this knolx session:  file system–based routing  endpoints (server-side functions)  hooks.

What are HTTP cookies? 02

What are HTTP cookies? Cookies, also known as HTTP cookies, are small text files that websites store on a user’s computer or mobile device.    These files contain data related to the user’s browsing activity on that website, such as login information, preferences, and shopping cart contents. Cookies can be either “session cookies” or “persistent cookies.” Session cookies are temporary and deleted when the user closes their browser, while persistent cookies remain on the user’s device until they expire or are deleted by the user.

Cookies in SvelteKit SvelteKit’s cookies have a new method for a cookie header, and also removed the getSession property, which returns the data that was set in user session.  With this new concept, it’s now much easier to work with cookies compared to adding payload manually to the request header. This update comes with a set of flexible methods, including set, get, and delete. Session management Persistence   Client-side storage Cross-domain compatibility Scalability Advantages of using cookies:

Disadvantages of using cookies Security concerns :  Care must be taken to properly sanitize input and validate data to prevent these types of security attacks Size limitations :  Cookies have a size limit of around 4KB, which may not be sufficient for storing larger amounts of data. This can limit the amount of data that can be stored on the client side Compatibility issues :  Some users may have cookies disabled or may be using older browsers that do not support cookies. This can limit the effectiveness of using cookies as a data storage mechanism

Understanding SvelteKit cookies methods 03

The 'set' method This method is used to set cookies in the  Set-Cookie  header and define options as needed, making the cookies available for recurring usage. To use the set method, you need to provide name , value, and option — option is optional. These config options allow us to specify various options that help ensure security and restriction to the cookie data:   cookies . set ( ' sessionId ' , "[email protected]" , {   httpOnly : true ,   sameSite : 'strict' ,   secure : false ,   path : '/' ,   maxAge : 60 * 60 * 24 * 7 });

The 'get' method This method is used to get cookie data that was previously set with  cookies.set , or from the request headers.  The get method takes two parameters: name and options, though options is optional:    cookies . get ( 'session' ); This method is used to delete a cookie from the browser.  Deleting a cookie removes the data and the expiry period attached to that cookie.  This method takes two parameters: name and options; again, options is optional:   await cookies . delete ( 'session' , { path : '/' }); The  'delete'  method ​ ​

Authentication using the parent() function 04

Authentication using the parent() function The parent() function is used to return props data from various load functions, then combine them together as one object.  Additionally, the  load  function is used to return data from the server/client to the Svelte template: // src /routes/+layout.server.js export const load = async ({ request , locals , cookies }) => {     return {         user : locals . user ,         welcome_message : "welcome back" ,     }; }; The +page.js is executed on the client side while the other files with .server.js are executed on the backend:   // src /routes/+page.js export const load = async ({ parent }) => {     const { user , welcome_message } = await parent ();     return {         user : user ,         message : welcome_message     };};

Implementing authentication with SvelteKit 05

Implementing authentication with SvelteKit   Setup First, we’ll initialize the SvelteKit project. npm create svelte@latest sveltekit -auth cd sveltekit -auth npm  install Authentication endpoints/workflow First, we need one additional library that will help us generate a random ID for each user:    npm i uuid

Svelte hooks Svelte hooks run on the server and allow us to extend the behavior of SvelteKit .  The handle hook runs on every request (and during prerendering). It gives us access to the request and allows us to modify the response. We can add custom data to  request.locals , which will be available in all endpoints. We will use it to parse the  session_id  cookie, retrieve the session, and attach the session data to  request.locals . The hook, which can also be referred to as a middleware, helps us handle the unauthorized user trying to access protected pages.

Securing routes and accessing the session on the client 06

Securing routes and accessing the session on the client In / src /routes/protected, we can create another route, called /protected that will only be accessible by authenticated users. We can then check if the session contains the user. If that’s not the case, the user isn’t signed in. We can redirect the user by returning the combination of HTTP status code 302 (found) and a redirect pointing to the route where the user should be redirected. Because the load function is running before the actual rendering of the page, an unauthenticated user will never see the page.

Securing routes and accessing the session on the client This is how the protected route looks: // src /routes/protected/+ page.svelte < script >   export let data ; </script> < svelte : head >   <title> Protected Page </title>   < meta name = "description" content = "About this app" /> </ svelte:head > <h1 class= "text-2xl font-semibold text-center" > Hi ! You are registered with email : { data . user . email }. </h1>

DEMO
Tags