dtgr3392 2016-01-21 10:40
浏览 114
已采纳

用于API的Laravel Middleware 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?

I am using Laravel 5.1

Thanks

  • 写回答

2条回答 默认 最新

  • dsfadsa08911 2016-01-21 11:29
    关注

    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);
        }
    }
    }
    

    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() {
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!