首頁  >  文章  >  web前端  >  在 Express 中使用 JWT 和指紋 Cookie 來防止 CSRF 和 XSS 攻擊

在 Express 中使用 JWT 和指紋 Cookie 來防止 CSRF 和 XSS 攻擊

Linda Hamilton
Linda Hamilton原創
2024-10-01 22:22:02279瀏覽

建置全端Web 應用程式時,客戶端和伺服器之間的通訊面臨不同漏洞的風險,例如XSS(跨站腳本)、 CSRF(跨站請求)偽造)和令牌劫持。 身為 Web 開發人員,了解此類漏洞以及如何預防它們非常重要。

由於我也在嘗試學習和預防 API 中的此漏洞,因此這些指南也是我創建本文的參考,這些都值得一讀:

  • 在前端處理 JWT 的終極指南
  • Java 備忘單的 JSON Web 令牌
  • OWASP Web 令牌劫持

首先,我們先定義一下前面提到的三個漏洞。

XSS(跨站腳本)

根據 OWASP.org

跨站腳本(XSS)攻擊是一種注入,其中惡意腳本被注入到其他良性且受信任的網站中。當攻擊者使用 Web 應用程式向不同的最終使用者發送惡意程式碼(通常以瀏覽器端腳本的形式)時,就會發生 XSS 攻擊。導致這些攻擊成功的缺陷相當普遍,並且發生在 Web 應用程式在其產生的輸出中使用使用者輸入而未對其進行驗證或編碼的任何地方。

CSRF(跨站請求偽造)

根據 OWASP.org

跨站請求偽造 (CSRF) 是一種攻擊,它會迫使最終使用者在目前經過驗證的 Web 應用程式上執行不必要的操作。在社會工程的幫助下(例如透過電子郵件或聊天發送連結),攻擊者可能會誘騙 Web 應用程式的使用者執行攻擊者選擇的操作。如果受害者是普通用戶,成功的 CSRF 攻擊可以迫使用戶執行狀態變更請求,例如轉移資金、更改電子郵件地址等。如果受害者是管理帳戶,CSRF 可以危害整個 Web 應用程式。

代幣劫持

依 JWT 備忘單

當攻擊者攔截/竊取令牌並使用目標使用者身分存取系統時,就會發生這種攻擊。


當我開始使用 Angular 和 Laravel 來建立全端應用程式。我使用 JSON Web Tokens (JWT) 進行身份驗證,它很容易使用,但如果實施不當也很容易被利用。我常犯的錯誤是:

1. 將代幣儲存在本地儲存

本地儲存是一種常見的選擇,因為它可以輕鬆地從JavaScript 檢索和訪問,它也是持久的,這意味著每當選項卡或瀏覽器關閉時它都不會刪除,這使得它非常容易受到跨站點的攻擊腳本(XSS) 攻擊。

例子:

如果 XSS 攻擊將以下內容注入您的網站:

console.log(localStorage.getItem('jwt_token'));

2. Token的TTL(Time to Live)長

JWT 有一個TTL,如果在Laravel 中沒有正確配置,預設情況下,令牌會設定為3600 秒(1 小時),為駭客提供了公開且廣泛的機會來竊取令牌並使用它充當受害者直到令牌過期。

3. 無刷新令牌

刷新令牌允許使用者取得新的存取令牌而無需重新進行身份驗證。 TTL 在 token 中起著至關重要的作用,前面提到過,較長的 TTL 存在安全風險,但較短的 TTL 會帶來糟糕的用戶體驗,迫使他們重新登入。


我們將創建一個基本的React Express應用程式來應用和緩解這些漏洞。為了更好地理解我們將要執行的應用程式的輸出,請參考下圖。

驗證

身份驗證時,使用者將發送使用者名稱和密碼並將其 POST 到 /login API 進行驗證。登入後,伺服器將:

  1. 驗證資料庫中的憑證

    JSON 格式的使用者憑證將在資料庫中檢查以進行身份驗證。

  2. 產生使用者指紋

    為已驗證的使用者產生隨機位元組指紋並將其儲存在變數中。

  3. 雜湊指紋

    產生的指紋將被散列並儲存在不同的變數中。

  4. 為產生的指紋(原始指紋)建立 Cookie

    未散列的指紋將設定在名為__Secure_Fgp 的硬化cookie 中,其標誌為:httpOnly、secure、sameSite=StrictmaxAge

    和maxAge為
  5. Creating a token for the User credentials with the Hashed Fingerprint

    Generating a JWT token for the verified user with its hashed fingerprint.

  6. Creating a cookie for the token

    After generating JWT token, the token will be sent as a cookie.

After the process, there will be 2 cookies will be sent, the original fingerprint of the user, and the generated token containing the data with the hashed fingerprint of the user.
Preventing CSRF and XSS Attacks with JWT and Fingerprint Cookies in Express

Accessing the protected route

When an authenticated user accessed the protected route. A middleware will verify the cookies of the user.

  1. Fetching cookies

    The middleware of the server will fetch the 2 cookies from the client upon request.

  2. Verify the JWT

    Using JWT token, it will verify the token from the fetched cookie. Extract the data inside the JWT (e.g. User details, fingerprint etc.)

  3. Hash the __Secure_Fgp cookie and compare it to the fingerprint from the payload JWT token.

Preventing CSRF and XSS Attacks with JWT and Fingerprint Cookies in Express

Now for the implementation


Server-Side (Express JS)

Here are all the libraries that we need:

  • jsonwebtoken

    For generating, signing and verifying JWT Tokens

  • crypto

    To generate random bytes and hashing fingerprints

  • cookie-parser

    For parsing Cookie header and creating cookies

  • cors

    Configuring CORS policy

  • csurf

    Generating CSRF Tokens

Set up

npm init -y //Initate a node project
// Installing dependencies
npm install express nodemon jsonwebtoken csurf crypto cookie-parser cors

Create a server.js file

Create a server.js file and edit the package.json, write "start": "nodemon server.js" under the scripts object.

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon server.js"
  },

Set up the server

Since we are using JWT, we’re gonna need a HMAC key

const express = require('express');
const jwt = require('jsonwebtoken');
const crypto = require('crypto');
const cookieParser = require('cookie-parser');
const cors = require('cors')
const csrf = require('csurf');
const csrfProtection = csrf({ cookie: true });

const app = express();

// MIDDLEWARES ======================================================
// Middleware to parse JSON bodies and Cookies
app.use(express.json());
app.use(cookieParser());

// Middleware to parse URL-encoded bodies (as sent by HTML forms)
app.use(express.urlencoded({ extended: true }));

// Middleware to apply CORS
const corsOptions = {
    origin: 'http://localhost:5173',  // Your React app's URL
    credentials: true  // Allow credentials (cookies, authorization headers)
};
app.use(cors(corsOptions));

const keyHMAC = crypto.randomBytes(64);  // HMAC key for JWT signing

// API ======================================================

// we'll add our routes here

// Start the Express server
app.listen(3000, () => {
    console.log('Server running on https://localhost:3000');
});

After setting up the Express server, we can start by creating our /login API.

Create a login API

I did not used database for this project, but feel free to modify the code.

app.post('/login', csrfProtection, (req, res) => {
        // Fetch the username and password from the JSON
    const { username, password } = req.body;

    // Mock data from the database
    // Assuming the user is registered in the database
    const userId = crypto.randomUUID();
    const user = {
        'id': userId,
        'username': username,
        'password': password,
    }

    res.status(200).json({
        message: 'Logged in successfully!',
        user: user
    });
});

Generate a user fingerprint

Assuming that the user is registered in the database, First, we’re gonna need two functions, one for generating a random fingerprint and hashing the fingerprint.

/* 
.
. ... other configurations
.
*/
const keyHMAC = crypto.randomBytes(64);  // HMAC key for JWT signing

// Utility to generate a secure random string
const generateRandomFingerprint = () => {
    return crypto.randomBytes(50).toString('hex');
};

// Utility to hash the fingerprint using SHA-256
const hashFingerprint = (fingerprint) => {
    return crypto.createHash('sha256').update(fingerprint, 'utf-8').digest('hex');
};

As discussed earlier, we are going to generate a fingerprint for the user, hash that fingerprint and set it in a cookie with the name __Secure_Fgp..

Then generate a token with the user’s details (e.g. id, username and password) together with the original fingerprint, not the hashed one since we are going to use that for verification of the token later.

    const userId = crypto.randomUUID();
    const user = {
        'id': userId,
        'username': username,
        'password': password,
    }

    const userFingerprint = generateRandomFingerprint();  // Generate random fingerprint
    const userFingerprintHash = hashFingerprint(userFingerprint);  // Hash fingerprint

    // Set the fingerprint in a hardened cookie
    res.cookie('__Secure_Fgp', userFingerprint, {
        httpOnly: true,
        secure: true,  // Send only over HTTPS
        sameSite: 'Strict',  // Prevent cross-site request
        maxAge: 15 * 60 * 1000  // Cookie expiration (15 minutes)
    });

    const token = jwt.sign(
        {
            sub: userId,  // User info (e.g., ID)
            username: username,
            password: password,
            userFingerprint: userFingerprintHash,  // Store the hashed fingerprint in the JWT
            exp: Math.floor(Date.now() / 1000) + 60 * 15  // Token expiration time (15 minutes)
        },
        keyHMAC // Signed jwt key
    );

    // Send JWT as a cookie
    res.cookie('token', token, {
        httpOnly: true,
        secure: true,
        sameSite: 'Strict',
        maxAge: 15 * 60 * 1000
    });

    res.status(200).json({
        message: 'Logged in successfully!',
        user: user
    });
});

After log in, it will pass two cookies, token and __Secure_Fgp which is the original fingerprint, into the front end.

Create middleware for authenticating of token

To validate that, we are going to create a middleware for our protected route. This middleware will fetch the two cookies first and validate, if there are no cookies sent, then it will be unauthorized.

If the token that was fetched from the cookie is not verified, malformed or expired, it will be forbidden for the user to access the route.

and lastly, it will hash the fingerprint from the fetched cookie and verify it with the hashed one.

// Middleware to verify JWT and fingerprint match
const authenticateToken = (req, res, next) => {
    const token = req.cookies.token;
    const fingerprintCookie = req.cookies.__Secure_Fgp;

    if (!token || !fingerprintCookie) {
        return res.status(401).json({
            status: 401,
            message: "Error: Unauthorized",
            desc: "Token expired"
        });  // Unauthorized
    }

    jwt.verify(token, keyHMAC, (err, payload) => {
        if (err) return res.status(403).json({
            status: 403,
            message: "Error: Forbidden",
            desc: "Token malformed or modified"
        });  // Forbidden

        const fingerprintHash = hashFingerprint(fingerprintCookie);

        // Compare the hashed fingerprint in the JWT with the hash of the cookie value
        if (payload.userFingerprint !== fingerprintHash) {
            return res.status(403).json({
                status: 403,
                message: "Forbidden",
                desc: "Fingerprint mismatch"
            });  // Forbidden - fingerprint mismatch
        }

        // Return the user info
        req.user = payload;
        next();
    });
};

To use this middleware we are going to create a protected route. This route will return the user that we fetched from the verified token in our middleware.

/* 
.
. ... login api
.
*/

// Protected route
app.get('/protected', authenticateToken, (req, res) => {
    res.json({ message: 'This is a protected route', user: req.user });
});

// Start the Express server
app.listen(3000, () => {
    console.log('Server running on https://localhost:3000');
});

With all of that set, we can now try it on our front end…


Client-Side integration (React + TS)

For this, I used some dependencies for styling. It does not matter what you used, the important thing is that we need to create a form that will allow the user to login.

I will not create a step by step in building a form, instead, I will just give the gist of the implementation for the client side.

In my React app, I used shadcn.ui for styling.

// App.tsx
<section className="h-svh flex justify-center items-center">
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8 p-7 rounded-lg w-96 border border-white">
            <h1 className="text-center font-bold text-xl">Welcome</h1>
            <FormField
              control={form.control}
              name="username"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Username</FormLabel>
                  <FormControl>
                    <Input placeholder="Username" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="password"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Password</FormLabel>
                  <FormControl>
                    <Input type="password" placeholder="Password" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <Button type="submit" className="mr-4">Login</Button>
            <Link to={"/page"} className='py-2 px-4 rounded-lg bg-white font-medium text-black'>Go to page</Link>
          </form>
        </Form>
      </section>

This is a simple login form with a button that will navigate the user to the other page that will fetch the protected route.

When the user click submit, it will POST request to the /login API in our server. If the response is success, it will navigate to the page.

 // App.tsx
  const onSubmit = async (values: z.infer<typeof formSchema>) => {
    console.log(values)
    try {
      const res = await fetch("http://localhost:3000/login", {
        method: 'POST', // Specify the HTTP method
        headers: {
          'Content-Type': 'application/json', // Set content type
        },
        credentials: 'include', // Include cookies in the request
        body: JSON.stringify(values), // Send the form data as JSON
      });
      if (!res.ok) {
        throw new Error(`Response status: ${res.status}`)
      }
      const result = await res.json();
      navigate("/page") // navigate to the page
      console.log(result);
    } catch (error) {
      console.error(error);
    }
  }

In the other page, it will fetch the /protected API to simulate an authenticated session of the user.

const fetchApi = async () => {
        try {
            const res = await fetch("http://localhost:3000/protected", {
                method: 'GET', // Specify the HTTP method
                headers: {
                    'Content-Type': 'application/json', // Set content type
                },
                credentials: 'include', // Include cookies in the request
            });

            if (!res.ok) {
                // Throw error
                throw res
            }
            // Fetch the response
            const result = await res.json();
            setUser(result.user);
            console.log(result)
        } catch (error: any) {
            setError(true)
            setStatus(error.status)
        }
    }

Make sure to put credentials: ‘include’ in the headers to include cookies upon request.

To test, run the app and look into the Application tab of the browser.

// React
npm run dev

// Express
npm start

Under Application tab, go to cookies and you can see the two cookies that the server generated.
Preventing CSRF and XSS Attacks with JWT and Fingerprint Cookies in Express

Token is good for 15 mins, and after that the user will need to reauthenticate.

With this, you have the potential prevention of XSS (Cross-Site Scripting) and Token Sidejacking into your application. This might not guarantee a full protection but it reduces the risks by setting the cookie based on the OWASP Cheat sheet.

res.cookie('__Secure_Fgp', userFingerprint, {
    httpOnly: true,
    secure: true,  // Send only over HTTPS
    sameSite: 'Strict',  // Prevent cross-site request
    maxAge: 15 * 60 * 1000
});

How about Cross-Site Request Forgery (CSRF) prevention?

For the CSRF, we are going to tweak a few things on our server side using this:

const csrf = require('csurf');
const csrfProtection = csrf({ cookie: true });

then we’ll add it to the middleware

// MIDDLEWARES ======================================================
// Middleware to parse JSON bodies and Cookies
app.use(express.json());
app.use(cookieParser());
// Middleware to parse URL-encoded bodies (as sent by HTML forms)
app.use(express.urlencoded({ extended: true }));

// Middleware to apply CORS
const corsOptions = {
    origin: 'http://localhost:5173',  // Your React app's URL
    credentials: true  // Allow credentials (cookies, authorization headers)
};
app.use(cors(corsOptions));

// Middleware to apply csrf protection
app.use(csrfProtection);

Create a CSRF Token API

For this we’ll need an API that will generate a CSRF Token and passed it as a cookie to the front end.

app.get('/csrf-token', (req, res) => { // Generate a CSRF token
    res.cookie('XSRF-TOKEN', req.csrfToken(), { // Sends token as a cookie
        httpOnly: false,
        secure: true,
        sameSite: 'Strict'
    });
    res.json({ csrfToken: req.csrfToken() });
});

Take note that this csrfProtection will only apply to the POST, PUT, DELETE requests, anything that will allow user to manipulate sensitive data. So for this, we’ll just secure our login endpoint with CSRF.

// Login route to generate JWT and set fingerprint
app.post('/login', csrfProtection, (req, res) => {
    const { username, password } = req.body;

    // Mock data from the database
    const userId = crypto.randomUUID();
    const user = {
        'id': userId,
        'username': username,
        'password': password,
    }

    /*
    .
    . other code
    .
    */

Generate the CSRF Token in the front end

We need to make a GET request to the /csrf-token API and save the token in our local storage.

// App.tsx
  useEffect(() => {
    const fetchCSRFToken = async () => {
      const res = await fetch('http://localhost:3000/csrf-token', {
        method: 'GET',
        credentials: 'include'  // Send cookies with the request
      });
      const data = await res.json();
      localStorage.setItem('csrfToken', data.csrfToken);
      setCsrfToken(data.csrfToken)
    };

    fetchCSRFToken();
  }, [])

I know, I know… we just talked about the security risk of putting tokens in a local storage. Since there are many ways to mitigate such attacks, common solution would be to refresh this token or just store it in the state variable. For now, we are going to store it in the local storage.

This will run when the component loads. everytime the user visits the App.tsx, it will generate a new CSRF Token.

Now since our /login API is protected with CSRF, we must include the CSRF-Token in the headers upon logging in.

  const onSubmit = async (values: z.infer<typeof formSchema>) => {
    console.log(values)
    try {
      const res = await fetch("http://localhost:3000/login", {
        method: 'POST', // Specify the HTTP method
        headers: {
          'Content-Type': 'application/json', // Set content type
          'CSRF-Token': csrfToken // adding the csrf token
        },
        credentials: 'include', // Include cookies in the request
        body: JSON.stringify(values), // Send the form data as JSON
      });
      if (!res.ok) {
        throw new Error(`Response status: ${res.status}`)
      }
      const result = await res.json();
      navigate("/page") // navigate to the page
      console.log(result);
    } catch (error) {
      console.error(error);
    }
  }

Now, when the App.tsx load, we can now see the Cookies in our browser.

Preventing CSRF and XSS Attacks with JWT and Fingerprint Cookies in Express

The XSRF-TOKEN is our generated token from the server, while the _csrf is the token generated by the csrfProtection = csrf({ cookie: true });

Here is the full code of the application.
https://github.com/Kurt-Chan/session-auth-practice

Conclusion

This might not give a full protection to your app but it reduce the risks of XSS and CSRF attacks in your website. To be honest, I am new to this integrations and still learning more and more about this.

If you have questions, feel free to ask!

THANK YOU FOR READING!

以上是在 Express 中使用 JWT 和指紋 Cookie 來防止 CSRF 和 XSS 攻擊的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn