Wave API Workaround
In my current needs for my application it would be easier for my users to just have to enter an API key and not worry about expiring tokens.
Would it be best to create a Middleware that creates a token from an API key with POST or GET request?
Is there any way to just avoid the access_token all together?
Ok, here's a solution to return the API response by only providing the API Key.
You will need to create a new Middleware file located at: app\Http\Middleware\ApiKeyMiddleware.php
, with the following contents:
<?php
namespace App\Http\Middleware;
use Closure;
use \App\User;
use \Wave\ApiKey;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Contracts\Auth\Factory as Auth;
class ApiKeyMiddleware
{
protected $auth;
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)
{
$api_key = ApiKey::where('key', '=', $request->key)->first();
// Get the API Key and user, then generate token and pass to Auth header
if(isset($api_key->id)){
$user = User::find($api_key->user_id);
$userToken=JWTAuth::fromUser($user);
$request->headers->add(['Authorization' => "Bearer $userToken"]);
}
return $next($request);
}
}
You will then need to load this middleware inside of your app\Http\Kernel.php
, inside of this file you will replace:
'api' => [
'throttle:60,1',
'bindings'
],
with:
'api' => [
\App\Http\Middleware\ApiKeyMiddleware::class,
'throttle:60,1',
'bindings'
],
This will load the new Middleware before your api routes and will verify a user based on an API key.
Now you will be able to hit any API route of your application and pass the key, /api/posts?key=LongApiKeyHere
, and the app will return the json data if the key is a valid key.
You may also want to track each time a user hits the API, so you can track the usage (this would be out of scope for wave, but it can be manually done).
Hope that helps.
Thanks.
That is what I was thinking would need to happen, a middleware of some sorts. Thanks for the help here.