我正在使用Slim Framework创建无状态REST API。在使用它之前,我在服务器端创建了一个SESSION,并在每个页面上进行会话检查。但现在,我不知道如何控制它。令牌身份验证Rest API会话
我在每个用户的数据库中都有一个api_key。在用户登录后,我用api_key回应并将用户重定向到index.php。但api_key不被保留。我怎样才能将api_key传递给每个使用Javascript的页面?原因是如果有人想要从我的REST API获取数据,他们必须向我发送一个api_key,并且如果用户登录之前我不想再次显示登录页面。
这里是我的REST API的一部分:
$app->post('/userlogin', function() use ($app) {
verifyRequiredParams(array('email', 'password'));
$email = $app->request->post('email');
$password = $app->request->post('password');
$objUserRegLog = new UserRegistrationLogin;
$result = $objUserRegLog->getUserByEmailAndPassword($email, $password);
if (!$result) {
$response["error"] = true;
$response["message"] = "Error! Invalid e-mail address or password.";
} else {
$response["error"] = false;
$response["id"] = $result["id"];
$response["email"] = $result["email"];
$response["api_key"] = $result["api_key"];
}
echoResponse(200, $response);
});
$app->get('/students', 'authenticateStudent', function() use ($app) {
$objStd = new Students;
$result = $objCases->getAllStudents();
if (!$result) {
$response["error"] = true;
$response["error_msg"] = "An error occured.";
$status_code = 404;
} else {
$response["error"] = false;
$response["cases"] = $result;
$status_code = 200;
}
echoResponse($status_code, $response);
});
function authenticateStudent(\Slim\Route $route) {
$headers = apache_request_headers();
$response = array();
$app = \Slim\Slim::getInstance();
if (isset($headers['Authorization'])) {
$db = new DbOperation();
$api_key = $headers['Authorization'];
if (!$db->isValidStudent($api_key)) {
$response["error"] = true;
$response["message"] = "Access Denied. Invalid Api key";
echoResponse(401, $response);
$app->stop();
}
} else {
$response["error"] = true;
$response["message"] = "Api key is misssing";
echoResponse(400, $response);
$app->stop();
}
}
而且随着AJAX调用:
$.signin = function() {
var inputVals = $("#form_signin").serialize();
$.ajax({
url : "api/v1/userlogin",
data : inputVals,
dataType : "json",
type : "post",
success : function(response) {
if (response.error) {
$(".popup").trigger("click");
$(".modal-title").html(response.message_title);
$(".modal-body").html(response.message);
} else {
window.location.href = "index.php";
}
console.log(response);
}
});
return false;
}
你为什么不使用cookies? –
@HéctorValverde Pareja你能举个例子吗? Cookies是否安全? – user3142206
@ user3142206如果您信任用户,则Cookie是安全的。对于令牌,它是完全没问题的。 – rottenoats