SlideShare a Scribd company logo
1 of 18
COURSE NAME: MERN STACK WEB
DEVELOPMENT(MSWD)
COURSE CODE: 22SDCS01R
TOPIC:CORS, AUTHENTICATION AND AUTHORIZATION, TOKEN BASED
AUTHENTICATION. BACKEND CONNECTIVITY WITH DATABASE AND
STORING INTO MONGODB.
1
CORS
CORS stands for Cross-Origin Resource Sharing. It is a security feature
implemented by web browsers that controls access to resources from
different origins (i.e., different domains) on the internet.
When a web page hosted on one domain requests a resource, such as an API
endpoint, from another domain, the browser checks if the resource's server
allows such cross-origin requests. If the server allows it, the browser
allows the request, but if not, the browser restricts the access due to the
same-origin policy, which is a security measure to prevent unauthorized
access to data.
2
CORS
CORS allows servers to specify which origins have permission to access their
resources by including specific HTTP headers in their responses. These headers
include:
Access-Control-Allow-Origin: Specifies which origins are allowed to access the
resource.
Access-Control-Allow-Methods: Specifies the HTTP methods (GET, POST,
PUT, DELETE, etc.) allowed when accessing the resource.
Access-Control-Allow-Headers: Specifies which HTTP headers can be used
when making the actual request.
3
CORS
Developers and server administrators need to configure their servers to
include these CORS headers in their responses to allow or restrict cross-
origin requests based on their requirements.
Enabling CORS is essential for web applications that need to access
resources (like APIs) from different domains to function properly while
maintaining security.
4
AUTHENTICATION
Authentication is the process of verifying a user’s identification through the acquisition of
credentialsand using those credentials to confirm the user’s identity. The authorization process
begins if the credentials are legitimate. The authorization process always follows the authentication
procedure. You were already aware of the authentication process because we all do it daily, whether
at work (logging into your computer) or at home (logging into a website). Yet, the truth is that most
“things” connected to the Internet require you to prove your identity by providing credentials.
5
AUTHORIZATION
Authorization is the process of allowing authenticated users access to resources by determining
whether they have system access permissions. By giving or denying specific licenses to an
authenticated user, authorization enables you to control access privileges. So, authorization
occurs after the system authenticates your identity, granting you complete access to resources
such as information, files, databases, funds, places, and anything else. That said, authorization
affects your capacity to access the system and the extent to which you can do so.
6
HOW TO BUILD AN AUTHENTICATION API
WITH JWT TOKEN IN NODE.JS
7
1. Set Up Your Node.js Project:
Create a new directory for your project, and initialize it with npm
(Node Package Manager):
mkdir jwt-auth-api
cd jwt-auth-api
npm init -y
Install necessary dependencies:
npm install express jsonwebtoken body-parser
HOW TO BUILD AN AUTHENTICATION API
WITH JWT TOKEN IN NODE.JS
8
2. Create a Basic Express Application:
Create a file named app.js (or any name you prefer) and set up your Express
application:
const express = require('express');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const app = express();
app.use(bodyParser.json());
const secretKey = 'your-secret-key'; // Change this to a strong, unique secret
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
HOW TO BUILD AN AUTHENTICATION API
WITH JWT TOKEN IN NODE.JS
9
3. Create User Model:
Create a simple user model (you can use a database for a real application, but for simplicity,
we'll use an array here):
const users = [
{ id: 1, username: 'user1', password: 'password1' },
{ id: 2, username: 'user2', password: 'password2' },
];
HOW TO BUILD AN AUTHENTICATION API
WITH JWT TOKEN IN NODE.JS
10
4. Implement User Authentication:
Create endpoints for user registration and login:
// User registration
app.post('/register', (req, res) => {
const { username, password } = req.body;
users.push({ id: users.length + 1, username, password });
res.json({ message: 'Registration successful' });
});
// User login
app.post('/login', (req, res) => {
const { username, password } = req.body;
const user = users.find((u) => u.username === username && u.password === password);
if (user) {
const token = jwt.sign({ username: user.username }, secretKey);
res.json({ message: 'Login successful', token });
} else {
res.status(401).json({ message: 'Authentication failed' });
}
});
HOW TO BUILD AN AUTHENTICATION API
WITH JWT TOKEN IN NODE.JS
11
5. Create Protected Routes:
Define a protected route that requires a valid JWT to access:
app.get('/protected', (req, res) => {
const token = req.header('Authorization');
if (!token) {
return res.status(401).json({ message: 'Authentication token is required' });
}
try {
const payload = jwt.verify(token, secretKey);
res.json({ message: 'Access granted', user: payload.username });
} catch (error) {
res.status(401).json({ message: 'Invalid token' });
}
});
HOW TO BUILD AN AUTHENTICATION API
WITH JWT TOKEN IN NODE.JS
12
6. Start the Server:
Start your server by running:
node app.js
Your authentication API is now up and running. You can use tools like Postman or curl to test the
endpoints:
• To register a user, send a POST request to /register.
• To log in and get a JWT, send a POST request to /login with valid user credentials.
• To access the protected route, send a GET request to /protected with the JWT in the
Authorization header.
BACK END CONNECTIVITY WITH DATABASE AND STORING
WITH MONGODB
13
• To establish backend connectivity with a database and store data using MongoDB, you can
follow these steps:
• Install MongoDB: If you haven't already, you need to install MongoDB on your server or
local machine. You can download it from the official MongoDB website and follow their
installation instructions.
• Start MongoDB: After installation, start the MongoDB service. On most systems, you can
start MongoDB with the following command:
BACK END CONNECTIVITY WITH DATABASE AND STORING
WITH MONGODB
14
• To establish backend connectivity with a database and store data using MongoDB, you can
follow these steps:
• Install MongoDB: If you haven't already, you need to install MongoDB on your server or
local machine. You can download it from the official MongoDB website and follow their
installation instructions.
• Start MongoDB: After installation, start the MongoDB service. On most systems, you can
start MongoDB with the following command:
BACK END CONNECTIVITY WITH DATABASE AND STORING
WITH MONGODB
15
Mongod
• This starts the MongoDB server and listens on the default port 27017.
• Choose a Backend Framework: You'll need a backend framework to interact with the
MongoDB database. Popular options include Node.js with Express, Python with Flask or
Django, and Java with Spring Boot.
• Install the MongoDB Driver for your Backend Language: Depending on your chosen backend
framework and programming language, you will need to install the corresponding MongoDB
driver or library. For example, if you're using Node.js, you can install the mongodb package
using npm:
npm install mongodb
BACK END CONNECTIVITY WITH DATABASE AND STORING
WITH MONGODB
16
Create a Connection to MongoDB: In your backend code, establish a connection to the
MongoDB server using the MongoDB driver. Here's an example in Node.js using the mongodb
package:
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017'; // MongoDB connection URL
MongoClient.connect(url, (err, client) => {
if (err) {
console.error('Failed to connect to MongoDB:', err);
return;
}
const db = client.db('your_database_name'); // Replace with your database name
// Now you can perform database operations here
});
BACK END CONNECTIVITY WITH DATABASE AND STORING
WITH MONGODB
17
Perform Database Operations: Once you've established a connection, you can perform various database
operations such as inserting, updating, deleting, and querying data. Here's an example of inserting data:
const collection = db.collection('your_collection_name'); // Replace with your collection name
const dataToInsert = { key: 'value' };
collection.insertOne(dataToInsert, (err, result) => {
if (err) {
console.error('Failed to insert data:', err);
} else {
console.log('Data inserted:', result.ops);
}
client.close(); // Close the MongoDB connection when done
});
THANK YOU
18

More Related Content

Similar to MSWD:MERN STACK WEB DEVELOPMENT COURSE CODE

MongoDB.local Sydney: Evolving your Data Access with MongoDB Stitch
MongoDB.local Sydney: Evolving your Data Access with MongoDB StitchMongoDB.local Sydney: Evolving your Data Access with MongoDB Stitch
MongoDB.local Sydney: Evolving your Data Access with MongoDB StitchMongoDB
 
UEMB200: Next Generation of Endpoint Management Architecture and Discovery Se...
UEMB200: Next Generation of Endpoint Management Architecture and Discovery Se...UEMB200: Next Generation of Endpoint Management Architecture and Discovery Se...
UEMB200: Next Generation of Endpoint Management Architecture and Discovery Se...Ivanti
 
Introduction to Blockchain and Hyperledger
Introduction to Blockchain and HyperledgerIntroduction to Blockchain and Hyperledger
Introduction to Blockchain and HyperledgerDev_Events
 
Single Sign-On for APEX applications based on Kerberos (Important: latest ver...
Single Sign-On for APEX applications based on Kerberos (Important: latest ver...Single Sign-On for APEX applications based on Kerberos (Important: latest ver...
Single Sign-On for APEX applications based on Kerberos (Important: latest ver...Niels de Bruijn
 
Implementing Microservices Security Patterns & Protocols with Spring
Implementing Microservices Security Patterns & Protocols with SpringImplementing Microservices Security Patterns & Protocols with Spring
Implementing Microservices Security Patterns & Protocols with SpringVMware Tanzu
 
MongoDB.local Dallas 2019: Pissing Off IT and Delivery: A Tale of 2 ODS's
MongoDB.local Dallas 2019: Pissing Off IT and Delivery: A Tale of 2 ODS'sMongoDB.local Dallas 2019: Pissing Off IT and Delivery: A Tale of 2 ODS's
MongoDB.local Dallas 2019: Pissing Off IT and Delivery: A Tale of 2 ODS'sMongoDB
 
Automation of web attacks from advisories to create real world exploits
Automation of web attacks from advisories to create real world exploitsAutomation of web attacks from advisories to create real world exploits
Automation of web attacks from advisories to create real world exploitsMunir Njiru
 
Hacking Client Side Insecurities
Hacking Client Side InsecuritiesHacking Client Side Insecurities
Hacking Client Side Insecuritiesamiable_indian
 
session and cookies.ppt
session and cookies.pptsession and cookies.ppt
session and cookies.pptJayaprasanna4
 
OWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxOWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxFernandoVizer
 
Parse cloud code
Parse cloud codeParse cloud code
Parse cloud code維佋 唐
 
Flask jwt authentication tutorial
Flask jwt authentication tutorialFlask jwt authentication tutorial
Flask jwt authentication tutorialKaty Slemon
 
DataPower Restful API Security
DataPower Restful API SecurityDataPower Restful API Security
DataPower Restful API SecurityJagadish Vemugunta
 
Web application penetration testing lab setup guide
Web application penetration testing lab setup guideWeb application penetration testing lab setup guide
Web application penetration testing lab setup guideSudhanshu Chauhan
 
It's a Dangerous World
It's a Dangerous World It's a Dangerous World
It's a Dangerous World MongoDB
 

Similar to MSWD:MERN STACK WEB DEVELOPMENT COURSE CODE (20)

MongoDB.local Sydney: Evolving your Data Access with MongoDB Stitch
MongoDB.local Sydney: Evolving your Data Access with MongoDB StitchMongoDB.local Sydney: Evolving your Data Access with MongoDB Stitch
MongoDB.local Sydney: Evolving your Data Access with MongoDB Stitch
 
UEMB200: Next Generation of Endpoint Management Architecture and Discovery Se...
UEMB200: Next Generation of Endpoint Management Architecture and Discovery Se...UEMB200: Next Generation of Endpoint Management Architecture and Discovery Se...
UEMB200: Next Generation of Endpoint Management Architecture and Discovery Se...
 
Firebase slide
Firebase slideFirebase slide
Firebase slide
 
Introduction to Blockchain and Hyperledger
Introduction to Blockchain and HyperledgerIntroduction to Blockchain and Hyperledger
Introduction to Blockchain and Hyperledger
 
Single Sign-On for APEX applications based on Kerberos (Important: latest ver...
Single Sign-On for APEX applications based on Kerberos (Important: latest ver...Single Sign-On for APEX applications based on Kerberos (Important: latest ver...
Single Sign-On for APEX applications based on Kerberos (Important: latest ver...
 
Implementing Microservices Security Patterns & Protocols with Spring
Implementing Microservices Security Patterns & Protocols with SpringImplementing Microservices Security Patterns & Protocols with Spring
Implementing Microservices Security Patterns & Protocols with Spring
 
MongoDB.local Dallas 2019: Pissing Off IT and Delivery: A Tale of 2 ODS's
MongoDB.local Dallas 2019: Pissing Off IT and Delivery: A Tale of 2 ODS'sMongoDB.local Dallas 2019: Pissing Off IT and Delivery: A Tale of 2 ODS's
MongoDB.local Dallas 2019: Pissing Off IT and Delivery: A Tale of 2 ODS's
 
presentation_finals
presentation_finalspresentation_finals
presentation_finals
 
IPCOM000242565D
IPCOM000242565DIPCOM000242565D
IPCOM000242565D
 
ASP.NET 13 - Security
ASP.NET 13 - SecurityASP.NET 13 - Security
ASP.NET 13 - Security
 
Automation of web attacks from advisories to create real world exploits
Automation of web attacks from advisories to create real world exploitsAutomation of web attacks from advisories to create real world exploits
Automation of web attacks from advisories to create real world exploits
 
Hacking Client Side Insecurities
Hacking Client Side InsecuritiesHacking Client Side Insecurities
Hacking Client Side Insecurities
 
session and cookies.ppt
session and cookies.pptsession and cookies.ppt
session and cookies.ppt
 
Old WP REST API, New Tricks
Old WP REST API, New TricksOld WP REST API, New Tricks
Old WP REST API, New Tricks
 
OWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxOWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptx
 
Parse cloud code
Parse cloud codeParse cloud code
Parse cloud code
 
Flask jwt authentication tutorial
Flask jwt authentication tutorialFlask jwt authentication tutorial
Flask jwt authentication tutorial
 
DataPower Restful API Security
DataPower Restful API SecurityDataPower Restful API Security
DataPower Restful API Security
 
Web application penetration testing lab setup guide
Web application penetration testing lab setup guideWeb application penetration testing lab setup guide
Web application penetration testing lab setup guide
 
It's a Dangerous World
It's a Dangerous World It's a Dangerous World
It's a Dangerous World
 

Recently uploaded

HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
High Profile Call Girls Dahisar Arpita 9907093804 Independent Escort Service ...
High Profile Call Girls Dahisar Arpita 9907093804 Independent Escort Service ...High Profile Call Girls Dahisar Arpita 9907093804 Independent Escort Service ...
High Profile Call Girls Dahisar Arpita 9907093804 Independent Escort Service ...Call girls in Ahmedabad High profile
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxhumanexperienceaaa
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 

Recently uploaded (20)

HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
High Profile Call Girls Dahisar Arpita 9907093804 Independent Escort Service ...
High Profile Call Girls Dahisar Arpita 9907093804 Independent Escort Service ...High Profile Call Girls Dahisar Arpita 9907093804 Independent Escort Service ...
High Profile Call Girls Dahisar Arpita 9907093804 Independent Escort Service ...
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 

MSWD:MERN STACK WEB DEVELOPMENT COURSE CODE

  • 1. COURSE NAME: MERN STACK WEB DEVELOPMENT(MSWD) COURSE CODE: 22SDCS01R TOPIC:CORS, AUTHENTICATION AND AUTHORIZATION, TOKEN BASED AUTHENTICATION. BACKEND CONNECTIVITY WITH DATABASE AND STORING INTO MONGODB. 1
  • 2. CORS CORS stands for Cross-Origin Resource Sharing. It is a security feature implemented by web browsers that controls access to resources from different origins (i.e., different domains) on the internet. When a web page hosted on one domain requests a resource, such as an API endpoint, from another domain, the browser checks if the resource's server allows such cross-origin requests. If the server allows it, the browser allows the request, but if not, the browser restricts the access due to the same-origin policy, which is a security measure to prevent unauthorized access to data. 2
  • 3. CORS CORS allows servers to specify which origins have permission to access their resources by including specific HTTP headers in their responses. These headers include: Access-Control-Allow-Origin: Specifies which origins are allowed to access the resource. Access-Control-Allow-Methods: Specifies the HTTP methods (GET, POST, PUT, DELETE, etc.) allowed when accessing the resource. Access-Control-Allow-Headers: Specifies which HTTP headers can be used when making the actual request. 3
  • 4. CORS Developers and server administrators need to configure their servers to include these CORS headers in their responses to allow or restrict cross- origin requests based on their requirements. Enabling CORS is essential for web applications that need to access resources (like APIs) from different domains to function properly while maintaining security. 4
  • 5. AUTHENTICATION Authentication is the process of verifying a user’s identification through the acquisition of credentialsand using those credentials to confirm the user’s identity. The authorization process begins if the credentials are legitimate. The authorization process always follows the authentication procedure. You were already aware of the authentication process because we all do it daily, whether at work (logging into your computer) or at home (logging into a website). Yet, the truth is that most “things” connected to the Internet require you to prove your identity by providing credentials. 5
  • 6. AUTHORIZATION Authorization is the process of allowing authenticated users access to resources by determining whether they have system access permissions. By giving or denying specific licenses to an authenticated user, authorization enables you to control access privileges. So, authorization occurs after the system authenticates your identity, granting you complete access to resources such as information, files, databases, funds, places, and anything else. That said, authorization affects your capacity to access the system and the extent to which you can do so. 6
  • 7. HOW TO BUILD AN AUTHENTICATION API WITH JWT TOKEN IN NODE.JS 7 1. Set Up Your Node.js Project: Create a new directory for your project, and initialize it with npm (Node Package Manager): mkdir jwt-auth-api cd jwt-auth-api npm init -y Install necessary dependencies: npm install express jsonwebtoken body-parser
  • 8. HOW TO BUILD AN AUTHENTICATION API WITH JWT TOKEN IN NODE.JS 8 2. Create a Basic Express Application: Create a file named app.js (or any name you prefer) and set up your Express application: const express = require('express'); const bodyParser = require('body-parser'); const jwt = require('jsonwebtoken'); const app = express(); app.use(bodyParser.json()); const secretKey = 'your-secret-key'; // Change this to a strong, unique secret app.listen(3000, () => { console.log('Server is running on port 3000'); });
  • 9. HOW TO BUILD AN AUTHENTICATION API WITH JWT TOKEN IN NODE.JS 9 3. Create User Model: Create a simple user model (you can use a database for a real application, but for simplicity, we'll use an array here): const users = [ { id: 1, username: 'user1', password: 'password1' }, { id: 2, username: 'user2', password: 'password2' }, ];
  • 10. HOW TO BUILD AN AUTHENTICATION API WITH JWT TOKEN IN NODE.JS 10 4. Implement User Authentication: Create endpoints for user registration and login: // User registration app.post('/register', (req, res) => { const { username, password } = req.body; users.push({ id: users.length + 1, username, password }); res.json({ message: 'Registration successful' }); }); // User login app.post('/login', (req, res) => { const { username, password } = req.body; const user = users.find((u) => u.username === username && u.password === password); if (user) { const token = jwt.sign({ username: user.username }, secretKey); res.json({ message: 'Login successful', token }); } else { res.status(401).json({ message: 'Authentication failed' }); } });
  • 11. HOW TO BUILD AN AUTHENTICATION API WITH JWT TOKEN IN NODE.JS 11 5. Create Protected Routes: Define a protected route that requires a valid JWT to access: app.get('/protected', (req, res) => { const token = req.header('Authorization'); if (!token) { return res.status(401).json({ message: 'Authentication token is required' }); } try { const payload = jwt.verify(token, secretKey); res.json({ message: 'Access granted', user: payload.username }); } catch (error) { res.status(401).json({ message: 'Invalid token' }); } });
  • 12. HOW TO BUILD AN AUTHENTICATION API WITH JWT TOKEN IN NODE.JS 12 6. Start the Server: Start your server by running: node app.js Your authentication API is now up and running. You can use tools like Postman or curl to test the endpoints: • To register a user, send a POST request to /register. • To log in and get a JWT, send a POST request to /login with valid user credentials. • To access the protected route, send a GET request to /protected with the JWT in the Authorization header.
  • 13. BACK END CONNECTIVITY WITH DATABASE AND STORING WITH MONGODB 13 • To establish backend connectivity with a database and store data using MongoDB, you can follow these steps: • Install MongoDB: If you haven't already, you need to install MongoDB on your server or local machine. You can download it from the official MongoDB website and follow their installation instructions. • Start MongoDB: After installation, start the MongoDB service. On most systems, you can start MongoDB with the following command:
  • 14. BACK END CONNECTIVITY WITH DATABASE AND STORING WITH MONGODB 14 • To establish backend connectivity with a database and store data using MongoDB, you can follow these steps: • Install MongoDB: If you haven't already, you need to install MongoDB on your server or local machine. You can download it from the official MongoDB website and follow their installation instructions. • Start MongoDB: After installation, start the MongoDB service. On most systems, you can start MongoDB with the following command:
  • 15. BACK END CONNECTIVITY WITH DATABASE AND STORING WITH MONGODB 15 Mongod • This starts the MongoDB server and listens on the default port 27017. • Choose a Backend Framework: You'll need a backend framework to interact with the MongoDB database. Popular options include Node.js with Express, Python with Flask or Django, and Java with Spring Boot. • Install the MongoDB Driver for your Backend Language: Depending on your chosen backend framework and programming language, you will need to install the corresponding MongoDB driver or library. For example, if you're using Node.js, you can install the mongodb package using npm: npm install mongodb
  • 16. BACK END CONNECTIVITY WITH DATABASE AND STORING WITH MONGODB 16 Create a Connection to MongoDB: In your backend code, establish a connection to the MongoDB server using the MongoDB driver. Here's an example in Node.js using the mongodb package: const MongoClient = require('mongodb').MongoClient; const url = 'mongodb://localhost:27017'; // MongoDB connection URL MongoClient.connect(url, (err, client) => { if (err) { console.error('Failed to connect to MongoDB:', err); return; } const db = client.db('your_database_name'); // Replace with your database name // Now you can perform database operations here });
  • 17. BACK END CONNECTIVITY WITH DATABASE AND STORING WITH MONGODB 17 Perform Database Operations: Once you've established a connection, you can perform various database operations such as inserting, updating, deleting, and querying data. Here's an example of inserting data: const collection = db.collection('your_collection_name'); // Replace with your collection name const dataToInsert = { key: 'value' }; collection.insertOne(dataToInsert, (err, result) => { if (err) { console.error('Failed to insert data:', err); } else { console.log('Data inserted:', result.ops); } client.close(); // Close the MongoDB connection when done });