adamtomat

Developer at Rareloop

Experience

2,960

0 Best Reply Awards

  • Member Since 2 Years Ago
  • 28 Lessons Completed
  • 5 Favorites

13th June, 2017

adamtomat left a reply on 5.2 - Password Reset For Multiple Tables • 2 months ago

I was building an API which handles password resets slightly differently to Laravel's out-the-box controllers.

To create a new token for an admin in the correct table, you can do this in your own controller (or anywhere):

// Find an admin
$admin = Admin::where('email', $request->input('email'))->first();

// Resolves an instance of "Illuminate\Auth\Passwords\PasswordBrokerManager", which lets you pick which broker you wish to use
$broker = app('auth.password')->broker('admins')->getRepository();

// Create the token
$token = $broker->create($admin);

23rd October, 2015

adamtomat left a reply on Excluding URI From CSRF Protection Not Working • 1 year ago

Thanks for clarifying why the cookie is needed and I get that we need the token for those methods you mentioned. But in the context of an API we're never using the token and end up sending unnecessary bytes down the wire on every request. That's why I would like to remove it. Just for API requests.

Even with $except = ['*'], it still adds the token to the headers for GET requests. I'd expect it to disable all CSRF related stuff for the given uri, including the setting of the Set-Cookie header.

22nd October, 2015

adamtomat started a new conversation Excluding URI From CSFR Protection Not Working • 1 year ago

According to the docs (5.1) it's possible to exclude URI's easily with the protected $except property, like so:

    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'api/*'
    ];

Here I am trying to exclude the Set-Cookie :XSRF-TOKEN from API requests. However, this isn't working.

So I dug into Illuminate\Foundation\Http\Middleware\VerifyCsrfToken and became really confused. By the looks of it, the exclude will be ignored on any GET request, and therefore you get a cookie set. Here's the handle method:

    public function handle($request, Closure $next)
    {
        if ($this->isReading($request) || $this->shouldPassThrough($request) || $this->tokensMatch($request)) {
            return $this->addCookieToResponse($request, $next($request));
        }

        throw new TokenMismatchException;
    }

isReading() will return true if the request is GET, rendering the results of shouldPassThrough() pointless. There is only 2 outcomes to this method too: 1) you get a cookie set, 2) you get an exception. I'd expect a third outcome of no cookie if the request matches an except item, right?

Also, looking at shouldPassThrough() seems backwards too. It returns true if the request matches an except item:

    /**
     * Determine if the request has a URI that should pass through CSRF verification.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function shouldPassThrough($request)
    {
        foreach ($this->except as $except) {
            if ($request->is($except)) {
                return true;
            }
        }

        return false;
    }

The method docs suggest that if it returns true it should pass through CSFR verification...i.e. get a cookie. But it only returns true if it matches an except item i.e. we don't want a cookie.

To get the behaviour I expect, I had to create my own addCookieToResponse method which only adds a cookie if the request doesn't match any except items;

    protected function addCookieToResponse($request, $response)
    {
        if (!$this->shouldPassThrough($request)) {
            $response = parent::addCookieToResponse($request, $response);
        }

        return $response;
    }

Can somebody either validate this (as a bug?), or explain to me how it is intended to work please? Because what the docs (and code) imply don't make sense to me.

22nd May, 2015

adamtomat left a reply on Catching All Exceptions Thrown In My API • 2 years ago

I've dug into the Request class and found a wantsJson method, which looks like it solves my issue in a better way. So if the request wants JSON, we return the exception in a JSON format. Much better!

Any feedback on the Response::json stuff though is appreciated still too.

public function render($request, Exception $e)
{
    // Determine if the current request is asking for JSON in return
    if($request->wantsJson()) {
        return Response::json([
            'status' => 'error',
            'error' => $e->getMessage(),
            'name' => get_class($e)
        ]);
    }

    return parent::render($request, $e);
}

And for reference, here's what wantsJson is doing under the hood:

/**
 * Determine if the current request is asking for JSON in return.
 *
 * @return bool
 */
public function wantsJson()
{
    $acceptable = $this->getAcceptableContentTypes();

    return isset($acceptable[0]) && $acceptable[0] == 'application/json';
}

adamtomat started a new conversation Catching All Exceptions Thrown In My API • 2 years ago

I'm building a small app, that has an API and an admin dashboard. My API routes are all prefixed with api/v1. I want to be able to catch all Exceptions that have been thrown by an API request, so I can return JSON instead of a view.

Reading online, I've seen people suggesting to do something like this:

if ($e instanceof APIException){
    return response(['success' => false, 'data' => [], 'message' => $e->getMessage(), 401);
}

But that only works if you know every Exception being thrown in your API, which in my opinion isn't very maintainable if your API is using plugins which are likely to throw their own Exceptions.

So my solution is to do the following in the app\Exceptions\Handler:render() method:

public function render($request, Exception $e)
{
// All Exceptions thrown by the API
    if($request->segment(1) === 'api') {
        return Response::json([
            'status' => 'error',
            'error' => $e->getMessage(),
            'name' => get_class($e)
        ]);
    }

    return parent::render($request, $e);
}

Is checking the request segment a good way of doing it?

Bonus points for a better way to return the json response with the correct HTTP status code too.

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.