(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
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
});