17: ال Authentication في جافاسكريبت

3 min read 9 days ago
Published on Aug 25, 2025 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

In this tutorial, we will explore authentication in JavaScript, focusing on how to implement it using an API. This is crucial for securing applications and managing user sessions. We will be using the Reqres API as our example for handling authentication processes.

Step 1: Understand Authentication Basics

Before diving into code, it's important to grasp the concept of authentication. It verifies who a user is and ensures that only authorized individuals can access certain resources. Key concepts include:

  • Login: Process where users provide credentials to access their accounts.
  • Token: A string representing the user's session, often used to maintain user state.

Step 2: Set Up Your Environment

To begin coding, ensure you have the following set up:

  • A text editor (like Visual Studio Code).
  • A web browser for testing.
  • Basic knowledge of JavaScript and HTML.

Step 3: Use the Reqres API

We will interact with the Reqres API for our authentication example. Follow these steps:

  1. Access the API:

    • Use the following endpoint for login:
      POST https://reqres.in/api/login
      
  2. Prepare a Sample Request:

    • You will need to send a JSON object containing the user's email and password. Here’s an example:
      {
        "email": "eve.holt@reqres.in",
        "password": "cityslicka"
      }
      

Step 4: Implementing the API Call

Now, let’s write the JavaScript code to handle the login request. Follow these steps:

  1. Set Up an HTML File:

    • Create an index.html file with a basic structure.
  2. Add JavaScript Code:

    • Use the Fetch API to send a request to the server:
      async function loginUser(email, password) {
          const response = await fetch('https://reqres.in/api/login', {
              method: 'POST',
              headers: {
                  'Content-Type': 'application/json'
              },
              body: JSON.stringify({ email, password })
          });
      
          if (response.ok) {
              const data = await response.json();
              console.log('Logged in successfully:', data);
          } else {
              console.error('Login failed:', response.statusText);
          }
      }
      
      // Example usage
      loginUser('eve.holt@reqres.in', 'cityslicka');
      

Step 5: Handle Responses

After sending the request, you need to handle the responses effectively:

  • Success: If the login is successful, handle the returned token for session management.
  • Error Handling: Provide user feedback for failed logins, such as incorrect credentials.

Step 6: Testing Your Implementation

Once your code is set up:

  1. Open your index.html file in a web browser.
  2. Check the console for the login status.
  3. Ensure you test both successful and unsuccessful login attempts.

Conclusion

In this tutorial, we covered the basics of authentication in JavaScript using the Reqres API. We learned how to send login requests, handle responses, and manage user sessions. This foundational knowledge is essential for building secure web applications.

Next steps could include implementing user registration, creating a logout function, and exploring more secure methods of authentication such as OAuth.