我创建了Web App,该Web App使用angular 4前端和Larvel Backend来创建Rest Api。
它使用通过令牌保护APi的中间件。 当用户从前端Angular登录时,将在后端(laravel)中生成“令牌”,该令牌存储在会话中并发送响应。登录标头“ Authorization”后,令牌会通过每个请求发送。
自定义控制器:LoginController
use Session;
class LoginController extends Controller
{
public function authenticate(Request $request)
{
//....validate user login data.....
$token = md5(uniqid(rand(), true));
Session::put('token', $token);
// ....send token in response...
}
}
中间件:RoleMiddleware
use Session;
class RoleMiddleware
{
public function handle($request, Closure $next)
{
$token = Session::get('token');
//why token appears empty here
$header = $request->header('Authorization');
if($header == $token){
return $next($request);
}
}
}
Api路线:
Route::post('login', 'Settings\LoginController@authenticate');
Route::get('users/get/{email}', 'UserController@profile')->middleware('token');
kernel.php:
class Kernel extends HttpKernel
{
protected $middleware = [
/////.........
......
.....
\Illuminate\Session\Middleware\StartSession::class,
];
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Session\Middleware\StartSession::class,
'throttle:60,1',
'bindings',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'token' => \App\Http\Middleware\RoleMiddleware::class,
];
}
答案 0 :(得分:2)
首先:API authentication
是无状态的,这意味着session/cookies
不用于对系统中的用户进行身份验证。
第二: Laravel会话仅在Web路由上启动,但是您可以将其切换为在api路由上启动,但我认为这里不是正确的选择。但是,如果要使其正常运行,请确保在启动RoleMiddleware之前先在api组上启动这些中间件。
'api' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\App\Http\Middleware\RoleMiddleware::class
'throttle:60,1',
'bindings',
];
第三步::使用[JWT Authentication][1]
link here(其中包括一个中间件)供您检查用户是否有权在您的api中执行操作。
通过在用户登录时简单生成JWT令牌并返回即可 该令牌成角度,您将令牌存储在前面 结束状态文件。
因此,在对后端的每个请求中,您都发送了JWT令牌,然后 JWT中间件将检查用户是否“登录”以执行特定操作 行动。