Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing The Laravel Passport/OAuth-Server Responses

I'm building an API in Laravel 5.4, using Laravel Passport 3 for authentication. All of my API methods return a set of values that are always returned, success, errors (if there are any errors) etc.

I've changed the response of a \Illuminate\Auth\AuthenticationException throws, to fit with the rest of my app, however I'm not sure how to change the response of various token grant responses, without doing something horrible like editing the vendor files.

like image 695
Daniel Dewhurst Avatar asked Jul 11 '17 09:07

Daniel Dewhurst


2 Answers

I think you can use middleware to change your response.

From laravel documentation:

Before & After Middleware

Whether a middleware runs before or after a request depends on the middleware itself.

You can capture the response and re-format the response.

You can use laravel's setContent method to set the content in response. Check here.

like image 65
Pankit Gami Avatar answered Sep 28 '22 15:09

Pankit Gami


What you are trying to do here is not supported by the library, so whatever you do will be hacky and will probably break the compatibility with future versions of laravel/passport.

In my opinion, you can only choose between those 2 options:

  1. Instead of declaring passport routes (Passport::routes()) you can declare equivalent routes to your custom methods. Those method internally calls Passport classes and methods, handling passport returning values before returning them to the user. It requires a lot of digging into passport code but, at the same time, if you only add some fields (success or error) you should be able to update your code without too much effort when updating the library.

  2. Fork laravel/passport and modify it to suit you needs. This solution in not as messy as the first, but a merge with new versions of passport in the future will probably be hard.

Of course, both are not great solutions. Keeping the standard passport responses or use a more suitable library are better options: I assume they are not feasible if you are asking.

like image 34
gbalduzzi Avatar answered Sep 28 '22 16:09

gbalduzzi