Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

joy014's avatar

Authentication via api_token and/or Session

So i am trying to access a data via API in 2 ways

  • Request made by AngularJS in-page (automatically has session cookies and token attached in it)
  • Request made via API request with api_token

The aim is for the controller to be the single place to handle both requests.

Is the below mentioned way Secure or am i doing something insecure. Please suggest otherwise.

I have appended Middleware\Authenticate.php

public function handle($request, Closure $next, $guard = null)
{
    if(Auth::guard('api')->user() != null || Auth::user() != null){
        return $next($request);
    }
    ....
}

And have this class Requests\AuthRequest.php

namespace App\Http\Requests;
use Illuminate\Support\Facades\Auth;

class AuthRequest extends Request {

    public $user;
    public function authorize()
    {
        if(Auth::guard('api')->user() != null){
            $this->user = Auth::guard('api')->user();
            return true;
        }
        if(Auth::user()){
            $this->user = Auth::user();
            return true;
        }
        return false;
    }

    public function rules()
    {
        return [];
    }

}

API class

class ApiController extends BaseController
{
    public function center_index(AuthRequest $r){
        $user = $r->user;
        ....
    }
    ....
}

Thanks very much in advance!

0 likes
1 reply
joy014's avatar
joy014
OP
Best Answer
Level 2

figured this out. Its safer to do normal API calls supported in L5.2

Please or to participate in this conversation.