ajax进阶教程:authentication和authorization两种验证方式区别以及样例

Published
2023-03-17
浏览次数 :  348

authentication header用于识别和验证提出请求的用户。这通常是使用标头中包含的令牌或会话ID来完成的。然后,服务器可以使用该信息来验证用户是否被授权访问所请求的资源。身份验证标头对于确保只有经过身份验证的用户才能访问敏感信息或执行需要身份验证的操作非常重要。

另一方面,authorization header用于指定用户被授权做什么或访问什么。例如,您可以包含一个指定用户角色或权限的授权标头。服务器然后可以使用该信息来确定用户是否被授权执行所请求的动作或访问所请求的资源。

因此,为了回答您的问题,问题不在于是否使用身份验证或授权标头,而在于何时根据应用程序的特定要求使用它们。如果需要验证发出请求的用户的身份,则应该使用authentication。如果您需要控制用户可以访问或做什么,则应该使用授权标头。

通常,将身份验证和授权标头同时使用是一种很好的做法,以确保只有经过身份验证和已授权的用户才能访问敏感资源或执行需要身份验证的操作。

beforeSend和headers的区别

我们通常给请求添加头部信息来进行验证或者授权,

beforeSend和headers都是向AJAX请求添加自定义header的有效方法。

在AJAX请求中使用headers选项更简单、更直接。您可以将所需的所有标头作为普通对象直接包含在headers选项中,如下所示:

$.ajax({
  url: "your_php_script.php",
  type: "POST",
  headers: {
    "Authorization": "Bearer " + authToken, 
    "Custom-Header": "value"
  },
  data: {
    // add any other data to be sent to the PHP script
  },
  success: function(response) {
    // handle the response from the PHP script
  },
  error: function(xhr, status, error) {
    // handle the error response from the PHP script
  }
});

如果您需要对标头的设置进行更细粒度的控制,那么使用beforeSend可能会很有用。例如,您可能希望根据某些条件有条件地添加标头,或修改现有标头。以下是如何使用beforeSend设置自定义标头的示例:

$.ajax({
  url: "your_php_script.php",
  type: "POST",
  beforeSend: function(xhr) {
    xhr.setRequestHeader("Custom-Header", "value");
    xhr.setRequestHeader("Authorization", "Bearer " + authToken);
  },
  data: {
    // add any other data to be sent to the PHP script
  },
  success: function(response) {
    // handle the response from the PHP script
  },
  error: function(xhr, status, error) {
    // handle the error response from the PHP script
  }
});

在本例中,在发送AJAX请求之前调用beforeSend函数,您可以使用xhr对象使用setRequestHeader()方法设置自定义标头。

一般来说,使用headers选项更简单、可读性更强,因此建议尽可能使用它。但是,如果您需要更多地控制如何设置标头,或者需要有条件地添加标头,则可以使用beforeSend。

PHP端验证方式

<?php

// Get the authentication token from the headers
if (!empty($_SERVER['HTTP_AUTHORIZATION'])) {
    $authToken = trim(str_replace('Bearer', '', $_SERVER['HTTP_AUTHORIZATION']));
} else {
    // No authentication token was sent, return an error
    http_response_code(401);
    die("Unauthorized");
}

// Validate the authentication token
// Your implementation here - this could involve checking a database or other data source
if ($authToken !== 'valid_token') {
    // The authentication token is invalid, return an error
    http_response_code(401);
    die("Unauthorized");
}

// Validate the authorization
// Your implementation here - this could involve checking user roles, permissions, or other criteria
if (/* authorization check fails */) {
    // The user is not authorized, return an error
    http_response_code(403);
    die("Forbidden");
}

// The authentication and authorization checks have passed, process the request
// Your implementation here - you can access the data sent in the AJAX request using the $_POST variable

你可以添加自定义函数来验证用户是否有权限

function userHasAccess($authToken) {
  // Your implementation here - this could involve checking user roles, permissions, or other criteria
  // For example, you could check if the user has the "admin" role
  if (getUserRole($authToken) === 'admin') {
    return true;
  } else {
    return false;
  }
}

如果使用authentication的验证方式:

<?php

// Get the authentication token from the headers
if (!empty($_SERVER['HTTP_AUTHENTICATION'])) {
    $authToken = trim(str_replace('Bearer', '', $_SERVER['HTTP_AUTHENTICATION']));
} else {
    // No authentication token was sent, return an error
    http_response_code(401);
    die("Unauthorized");
}

// Validate the authentication token
// Your implementation here - this could involve checking a database or other data source
if ($authToken !== 'valid_token') {
    // The authentication token is invalid, return an error
    http_response_code(401);
    die("Unauthorized");
}

// The authentication token is valid, process the request
// Your implementation here - you can access the data sent in the AJAX request using the $_POST variable

下面是用basic验证方法重写

ajax

$.ajax({
  url: "your_php_script.php",
  type: "POST",
  beforeSend: function(xhr) {
    var authHeader = "Basic " + btoa(username + ":" + password); // add the Basic authentication header
    xhr.setRequestHeader("Authentication", authHeader); // add the authentication header
  },
  data: {
    // add any other data to be sent to the PHP script
  },
  success: function(response) {
    // handle the response from the PHP script
  },
  error: function(xhr, status, error) {
    // handle the error response from the PHP script
  }
});

php

<?php

// Get the authentication credentials from the headers
if (!empty($_SERVER['HTTP_AUTHENTICATION'])) {
    $authHeader = trim($_SERVER['HTTP_AUTHENTICATION']);
} else {
    // No authentication credentials were sent, return an error
    http_response_code(401);
    die("Unauthorized");
}

// Validate the authentication credentials
if (strpos($authHeader, 'Basic') !== 0) {
    // The authentication credentials are not in the correct format, return an error
    http_response_code(401);
    die("Unauthorized");
}

list($username, $password) = explode(':', base64_decode(substr($authHeader, 6)));

// Your implementation here - this could involve checking a database or other data source to validate the credentials
if (!validateCredentials($username, $password)) {
    // The authentication credentials are invalid, return an error
    http_response_code(401);
    die("Unauthorized");
}

// The authentication check has passed, process the request
// Your implementation here - you can access the data sent in the AJAX request using the $_POST variable

自定义验证的php函数

可以来实现授权,$valid_users可以是你网站里的生成的token

function validateCredentials($username, $password) {
  // Hard-coded list of valid users and passwords
  $valid_users = array(
    'user1' => 'password1',
    'user2' => 'password2',
    'user3' => 'password3'
  );

  // Check if the username exists in the list of valid users
  if (array_key_exists($username, $valid_users)) {
    // If the username exists, check if the password matches
    if ($valid_users[$username] == $password) {
      // If the password matches, return true to indicate that the credentials are valid
      return true;
    }
  }

  // If the username or password is invalid, return false to indicate that the credentials are invalid
  return false;
}

标签:, ,
Top