0
即時新的流明和im試圖通過放置一個名爲Api-Token的代碼來保護我的註冊api,以便只有知道該代碼的用戶才能創建一個新用戶,但每次我嘗試創建一個新用戶時,做在流明中保證API的安全
這裏是香港專業教育學院迄今所做
中間件/身份驗證
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;
use App\User;
class Authenticate
{
/**
* The authentication guard factory instance.
*
* @var \Illuminate\Contracts\Auth\Factory
*/
protected $auth;
/**
* Create a new middleware instance.
*
* @param \Illuminate\Contracts\Auth\Factory $auth
* @return void
*/
public function __construct(Auth $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if ($this->auth->guard($guard)->guest()) {
if ($request->has('api_token')) {
$token = $request->input('api_token');
$check_token = User::where('api_token', $token)->first();
if ($check_token == null) {
$res['success'] = false;
$res['message'] = 'Permission not allowed!';
return response($res);
}
}else{
$res['success'] = false;
$res['message'] = 'Unauthorized!';
return response($res);
}
}
return $next($request);
}
}
AuthServiceProvider
<?php
namespace App\Providers;
use App\User;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{ /** *註冊任何應用程序服務。 * * @返回無效 */ 公共功能寄存器(){ }
/**
* Boot the authentication services for the application.
*
* @return void
*/
public function boot()
{
// Here you may define how you wish users to be authenticated for your Lumen
// application. The callback which receives the incoming request instance
// should return either a User instance or null. You're free to obtain
// the User instance via an API token or any other method necessary.
// $this->app['auth']->viaRequest('api', function ($request) {
// $header = $request->header('Api-Token');
// if ($header && $header == 'bird is a word') {
// return new User();
// }
// return null;
$this->app['auth']->viaRequest('api', function ($request) {
if ($request->input('api_token')) {
return User::where('api_token', $request->input('api_token'))->first();
}
});
}
}
路線
<?php
$app->get('/', function() use ($app) {
$res['success'] = true;
$res['result'] = "Hello there welcome to web api using lumen tutorial!";
return response($res);
});
$app->post('/login', '[email protected]');
$app->post('/register', ['middleware' => 'auth', 'uses' => '[email protected]']);
$app->get('/user/{id}', ['middleware' => 'auth', 'uses' => '[email protected]_user']);