使用 php Slim 框架实现访问控制认证
Posted
技术标签:
【中文标题】使用 php Slim 框架实现访问控制认证【英文标题】:implementing access control authentication with php Slim framework 【发布时间】:2017-10-11 16:21:05 【问题描述】:我正在为我的应用后端使用 php 和 slim 构建一个 restful api,而且我们有一个 web 版本,但我的团队使用纯 php 和 web 套装,我们分开工作。这只是我第一次承担后端责任 我对如何以安全和专业的方式处理身份验证有一个误解 我已经阅读了这个article 但我需要一个详细的方法来实现它在 php & slim 并将其扩展到 web 团队,以便使用相同的身份验证技术。
这是我使用的登录/注册代码: 帮我改进它:
$app->post('/api/create_user', function( $request , $response , $args )
require('../config.php');
$email = $_POST['email'];
$qry= "select * from user where email ='". $email."'";
$result=$mysqli->query($qry);
if(mysqli_num_rows($result)>0)
$user = new stdClass();
$user->status=0;
$user->error=" the email is registered ";
$result = new stdClass();
$result->result=$user;
else
$password = md5($_POST['password']);
$image=$_FILES['image']['name'];
$email=$_POST['email'] ;
$nickname =$_POST['nickname'];
$birthDay=$_POST['birthdate'];
$insert_req="INSERT INTO user VALUES ('', '$email', '$password','$nickname')";
$insert_user_result=$mysqli->query($insert_req);
if ($insert_user_result)
$user = new stdClass();
$user->status=1;
$result = new stdClass();
$result->result=$user;
else $user = new stdClass();
$user->status=2;
$user->error=mysql_error();
$result = new stdClass();
$result->result=$user;
if (isset($result))
header('Content-type: application/json');
echo json_encode($result);
);
?>
<?php
$app->post('/api/login', function( $request , $response , $args )
require('../config.php');
$email =$_POST['email'];
$password = md5($_POST['password']);
$findemail_qry= "select user_id from user where email ='". $email."'";
$findemail_result =$mysqli->query($findemail_qry);
if(mysqli_num_rows($findemail_result)>0)
$login_qry="select user_id from user where email ='". $email."'AND password ='".$password."'";
$login_result =$mysqli->query($login_qry);
if(mysqli_num_rows($login_result)>0)
$data =mysqli_fetch_assoc ($login_result);
$user_id=$data['user_id'];
$user = new stdClass();
$user->status=1;
$user->user_id=$user_id;
$result = new stdClass();
$result->result=$user;
else
$user = new stdClass();
$user->status=2;
$user->error="wrong password";
$result = new stdClass();
$result->result=$user;
else
$user = new stdClass();
$user->status=0;
$user->error=" this email not registered ";
$result = new stdClass();
$result->result=$user;
if (isset($result))
header('Content-type: application/json');
echo json_encode($result);
);
?>
【问题讨论】:
您可能想查看 API 框架以获取灵感。 github.com/tuupola/slim-api-skeleton 【参考方案1】:您可以在您的超薄应用程序中使用 JWT 作为您 API 的身份验证层
你可以使用这个库来实现它 Slim JWT
你可以用一种简单的方式来使用这样的东西
尝试使用基本授权发送用户名和密码 然后您将生成一个新的 JWT 令牌,它将用于所有其他 API
<?php
use \Firebase\JWT\JWT;
use \Slim\Middleware\HttpBasicAuthentication\AuthenticatorInterface;
require '../vendor/autoload.php';
$app = new \Slim\App;
class RandomAuthenticator implements AuthenticatorInterface
public function __invoke(array $arguments)
//validation for user and password
$Password=$arguments['password'];
$user=$arguments['user'];
if(($Password=="admin") &&($user=="admin") )
return true;
else
return false ;
//add http basic middleware for login route
$app->add(new \Slim\Middleware\HttpBasicAuthentication([
"path" => "/login",
"realm" => "Protected",
"authenticator" => new RandomAuthenticator()
]));
$app->post("/login", function ($request, $response, $arguments)
//generate JWT token
$now = new DateTime();
$future = new DateTime("now +20 minutes");
$server = $request->getServerParams();
$payload = [
"iat" => $now->getTimeStamp(),
"exp" => $future->getTimeStamp(),
"sub" => $server["PHP_AUTH_USER"],
];
$secret = "TOURSECERTKEY";
$token = JWT::encode($payload, $secret, "HS512");
$data["status"] = "ok";
$data["token"] = $token;
return $response->withStatus(201)
->withHeader("Content-Type", "application/json")
->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
);
//Add jWT token Authorization middleware for all API
$app->add(new \Slim\Middleware\JwtAuthentication([
"path" => ["/"],
"passthrough" => ["/login"],
"secret" => "TOURSECERTKEY",
"error" => function ($request, $response, $arguments)
$data["status"] = "error";
$data["message"] = $arguments["message"];
return $response
->withHeader("Content-Type", "application/json")
->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
]));
【讨论】:
以上是关于使用 php Slim 框架实现访问控制认证的主要内容,如果未能解决你的问题,请参考以下文章