mpociot / laravel-apidoc-generator

Laravel API Documentation Generator
https://beyondco.de/docs/laravel-apidoc-generator/
MIT License
3.43k stars 614 forks source link

Example on passing bearer token to generate succesful response #738

Closed ajcastro closed 4 years ago

ajcastro commented 4 years ago

use App\User;
use Illuminate\Routing\Route;
use Mpociot\ApiDoc\Extracting\Strategies\Responses\ResponseCalls;

class MyResponseCalls extends ResponseCalls
{
    protected function prepareRequest(Route $route, array $rulesToApply, array $urlParams, array $bodyParams, array $queryParams, array $headers)
    {
        $request = parent::prepareRequest($route, $rulesToApply, $urlParams, $bodyParams, $queryParams, $headers);

        if (in_array('auth:api', $route->gatherMiddleware())) {
            $user = factory(User::class)->create();
            $token = auth()->fromUser($user);

            $request->headers->set('Authorization', "Bearer {$token}");
        }

        return $request;
    }
}

Then replace \Mpociot\ApiDoc\Extracting\Strategies\Responses\ResponseCalls in the config in apidoc -> strategies -> responses.

shalvah commented 4 years ago

That's nice! Thanks for adding it. The new version (will be made public soon) has better support for authentication as well, but not to this extent. We'll soon add a wiki where people can add useful snippets like this.

shalvah commented 4 years ago

@ajcastro I've added your strategy to the new community wiki at https://github.com/knuckleswtf/scribe/wiki/Helpful-strategies-(snippets)#authenticating-as-a-particular-user-for-response-calls. Feel free to update it or add more.👍