适用于API的Laravel中间件Auth [英] Laravel Middleware Auth for API

查看:200
本文介绍了适用于API的Laravel中间件Auth的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在开发和应用程序,该应用程序具有一个API,希望通过中间件访问该API,该API将检查用户是否使用Laravel的默认Auth中间件和Tymone的JWT.Auth令牌中间件进行身份验证,因此请求可以通过以下任意一种进行身份验证方法.

I am currently developing and application that has an API which I want to be accessible through middleware that will check if the user is authenticated using either Laravel's default Auth middleware and Tymone's JWT.Auth token based middleware so requests can be authenticated either of the ways.

我可以弄清楚如何拥有一个或另一个,但不能同时拥有两个,我该怎么做?我在想我需要创建一个使用这些现有中间件的自定义中间件吗?

I can work out how to have one or the other but not both, how could I do this? I'm thinking I need to create a custom middleware that uses these existing middlewares?

我正在使用Laravel 5.1

I am using Laravel 5.1

谢谢

推荐答案

结果我确实需要制作自己的中间件,该中间件比我想象的要容易:

Turns out I did need to make my own middleware which was easier than I thought:

<?php

namespace App\Http\Middleware;

use Auth;
use JWTAuth;
use Closure;

class APIMiddleware {

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next) {        
    try {
        $jwt = JWTAuth::parseToken()->authenticate();
    } catch (\Tymon\JWTAuth\Exceptions\JWTException $e) {
        $jwt = false;
    }
    if (Auth::check() || $jwt) {
        return $next($request);
    } else {
        return response('Unauthorized.', 401);
    }
}
}

然后在内核中注册后,像这样在api路由组上使用此中间件:

Then I use this middleware on my api route group like so after registering in the kernel:

Route::group(['prefix' => 'api', 'middleware' => ['api.auth']], function() {

这篇关于适用于API的Laravel中间件Auth的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆