0Pricing
WebSockets & Realtime Systems Programming · บทเรียน

การตรวจสอบสิทธิ์และการอนุญาต

ผสานกลไกการตรวจสอบสิทธิ์ เช่น JWT ระหว่างการจับมือเชื่อมต่อ และจัดการสิทธิ์ของผู้ใช้สำหรับข้อความ WebSocket

การตรวจสอบสิทธิ์และการอนุญาต เป็นบทเรียน WebSockets & Realtime Systems Programming ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน WebSockets & Realtime Systems Programming และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส WebSockets & Realtime Systems Programming มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Securing WebSocket Interactions

WebSockets enable powerful real-time communication. But just like any web interaction, we need to know who is connecting and what they are allowed to do.

This is where authentication and authorization come in. They are crucial for building secure and reliable applications.

Auth Challenges for WebSockets

Unlike traditional HTTP requests, which are stateless and often carry authentication headers with each request, WebSockets establish a persistent, stateful connection.

This means we authenticate once during the initial connection handshake, and then the server must remember the client's identity for the duration of the connection.

Authentication During Handshake

The perfect moment to authenticate a client is during the WebSocket handshake. This is the initial HTTP request that upgrades to a WebSocket connection.

  • The client sends an HTTP GET request with a Upgrade: websocket header.
  • The server can inspect this request for authentication credentials before deciding to upgrade.
  • If credentials are valid, the connection is established; otherwise, it's rejected.

Passing Credentials: Query Params

One way to pass credentials is via query parameters in the WebSocket URL. For example: ws://server.com/chat?token=your_jwt.

  • Pros: Simple to implement.
  • Cons: Can expose sensitive tokens in server logs or browser history. Generally less secure and not recommended for production.

Passing Credentials: HTTP Headers

A more secure and recommended approach is to pass authentication tokens within HTTP headers during the handshake.

While the standard WebSocket API doesn't directly support custom headers, some libraries or proxy configurations allow this. Often, custom headers like Authorization: Bearer your_jwt are used, or tokens are embedded in the Sec-WebSocket-Protocol header.

What is a JSON Web Token (JWT)?

A JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. It's often used for authentication.

  • It's digitally signed, ensuring its authenticity.
  • It contains user information (like user ID, roles) in a payload.
  • The server verifies the JWT signature to confirm the user's identity.

Server-Side JWT Handshake (Node.js)

Here's a simplified Node.js example using the ws library showing how a server might verify a JWT from a query parameter during the handshake. In a real app, you'd use a robust JWT library.

const WebSocket = require('ws');
const url = require('url');

const wss = new WebSocket.Server({ noServer: true });

wss.on('connection', function connection(ws, request) {
  const userId = request.userId; // Set during handshake verification
  console.log(`Client ${userId} connected`);

  ws.on('message', function incoming(message) {
    console.log(`Received from ${userId}: ${message}`);
  });

  ws.on('close', () => console.log(`Client ${userId} disconnected`));
});

// This is where you would integrate with an HTTP server
// For simplicity, we'll simulate the handshake here.

// Simulate an HTTP server upgrade listener
// In a real app, this would be an http.Server.on('upgrade')
function handleUpgrade(request, socket, head) {
  const pathname = url.parse(request.url).pathname;

  if (pathname === '/ws') {
    const token = new URLSearchParams(url.parse(request.url).query).get('token');
    
    // --- Simulate JWT verification ---
    if (token === 'valid_jwt_123') {
      request.userId = 'user_1'; // Attach user info to request
      wss.handleUpgrade(request, socket, head, function done(ws) {
        wss.emit('connection', ws, request);
      });
    } else {
      console.log('Invalid JWT. Connection rejected.');
      socket.destroy();
    }
  } else {
    socket.destroy();
  }
}

// Example usage (not a full http server, just for demonstration)
const mockRequest = {
  url: '/ws?token=valid_jwt_123',
  headers: { 'upgrade': 'websocket', 'connection': 'upgrade' }
};
const mockSocket = { 
  destroy: () => console.log('Socket destroyed (connection rejected)') 
};
const mockHead = Buffer.alloc(0);

console.log('Attempting connection with valid token...');
handleUpgrade(mockRequest, mockSocket, mockHead);

// Attempt connection with invalid token
const mockInvalidRequest = {
  url: '/ws?token=invalid_jwt',
  headers: { 'upgrade': 'websocket', 'connection': 'upgrade' }
};
const mockInvalidSocket = { 
  destroy: () => console.log('Socket destroyed (connection rejected)') 
};
console.log('\nAttempting connection with invalid token...');
handleUpgrade(mockInvalidRequest, mockInvalidSocket, mockHead);

Authorization: Who Can Do What?

Once a user is authenticated (we know who they are), authorization determines what actions they are permitted to perform.

This often involves checking user roles or permissions associated with their authenticated identity. For example, a 'guest' user might only be able to read messages, while an 'admin' can also delete them.

Message-Level Authorization (Node.js)

After a WebSocket connection is established and the user is authenticated, the server can enforce authorization rules on incoming messages. This example shows a simple check based on a user's role.

const WebSocket = require('ws');

// Simulate a WebSocket server for demonstration
const wss = new WebSocket.Server({ port: 8080 });

// In a real application, user info (like roles) would be
// stored in the ws object after successful authentication.
const connectedClients = new Map(); // Map ws -> { userId, role }

wss.on('connection', function connection(ws) {
  // Simulate authenticated user and their role
  const userId = `user_${Math.floor(Math.random() * 100)}`;
  const role = (userId === 'user_10') ? 'admin' : 'member';
  connectedClients.set(ws, { userId, role });

  console.log(`Client ${userId} (${role}) connected.`);
  ws.send(`Welcome, ${userId}! Your role is ${role}.`);

  ws.on('message', function incoming(message) {
    const clientInfo = connectedClients.get(ws);
    const msg = message.toString();

    console.log(`Received from ${clientInfo.userId}: ${msg}`);

    // --- Authorization Check ---
    if (msg.startsWith('/delete') && clientInfo.role !== 'admin') {
      ws.send('Error: You are not authorized to delete messages.');
      console.log(`${clientInfo.userId} (member) tried to delete.`);
    } else if (msg.startsWith('/delete') && clientInfo.role === 'admin') {
      ws.send('Message deleted successfully!');
      console.log(`${clientInfo.userId} (admin) deleted a message.`);
      // In a real app, delete logic would go here
    } else {
      // Broadcast message to others or process normally
      wss.clients.forEach(function each(client) {
        if (client !== ws && client.readyState === WebSocket.OPEN) {
          client.send(`${clientInfo.userId}: ${msg}`);
        }
      });
      ws.send(`You said: ${msg}`);
    }
  });

  ws.on('close', () => {
    const clientInfo = connectedClients.get(ws);
    console.log(`Client ${clientInfo.userId} disconnected.`);
    connectedClients.delete(ws);
  });
});

console.log('WebSocket server started on port 8080. Try connecting with a WebSocket client!');
console.log('Simulated user_10 is an admin, others are members.');

Auth & Auth Quick Check

When is the most appropriate and secure time to authenticate a client in a WebSocket connection?

Recap: Secure Connections

We've explored how to secure WebSocket connections by implementing authentication and authorization.

  • Authentication happens primarily during the handshake, often using JWTs passed in headers.
  • Authorization determines user permissions, controlling what actions they can take over the established connection.
  • These mechanisms are vital for protecting your real-time applications from unauthorized access and actions.

คำถามที่พบบ่อย

บทเรียน “การตรวจสอบสิทธิ์และการอนุญาต” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การตรวจสอบสิทธิ์และการอนุญาต” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส WebSockets & Realtime Systems Programming ให้อัปเกรดเป็น CoddyKit PRO คอร์ส WebSockets & Realtime Systems Programming มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การตรวจสอบสิทธิ์และการอนุญาต”

ผสานกลไกการตรวจสอบสิทธิ์ เช่น JWT ระหว่างการจับมือเชื่อมต่อ และจัดการสิทธิ์ของผู้ใช้สำหรับข้อความ WebSocket คุณปฏิบัติ WebSockets & Realtime Systems Programming ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน WebSockets & Realtime Systems Programming หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน WebSockets & Realtime Systems Programming บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “การตรวจสอบสิทธิ์และการอนุญาต” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน WebSockets & Realtime Systems Programming นี้ได้ไหม

ได้ บทเรียน WebSockets & Realtime Systems Programming ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. WebSocket Secure (WSS) และ TLS
  2. การตรวจสอบสิทธิ์และการอนุญาต
  3. การป้องกันการโจมตี WebSocket ที่พบบ่อย
  4. การจำกัดอัตราและการป้องกันการใช้งานในทางที่ผิด
← กลับไปที่ WebSockets & Realtime Systems Programming