Digging Deeper

Authorizations

Laravel Rest Api exposes a lot of information and it is crucial for your applications to secure the access to resources. Thankfully, Laravel Rest Api seamlessly integrates with Laravel, ensuring a straightforward approach to securing your API.
Laravel Rest Api doesn't provide authentication, you can define it on your project using for example Laravel Passport, Laravel Sanctum or make your own.

Policies

To restrict access to viewing, creating, updating, or deleting resources, Laravel Rest Api leverages Laravel's authorization policies. Basically, if your model is associated with a policy in your AppServiceProvider, Laravel Rest API will automatically use it, requiring no further configuration.

This concerns the following methods:

  • viewAny
  • view
  • create
  • update
  • replicate
  • delete
  • restore
  • forceDelete

For example, to determine which users are allowed to view a User model, you simply need to define a view method on the model's corresponding policy class:

<?php

namespace App\Policies;

use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class UserPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can view the user.
     *
     * @param  \App\Models\User  $user
     * @param  \App\Models\User  $model
     * @return mixed
     */
    public function view(User $user, User $model)
    {
        return $user->is($model);
    }
}

Disable Authorizations

By default, authorizations are enabled but you can disable them in certain situations.

When you are mutating / searching distant relations, this will apply the relation resource state.

Globally

In your config/rest.php file, you can directly specify to disable this feature:

[
    // ...
    'authorizations' => [
        'enabled' => false, // Switch this to false
    ]
    // ...
]

Resource

If you want to disable this feature for certain resources only, you can use the DisableAuthorizations trait on your resource file:

UserResource.php
class UserResource extends Resource
{
    use \Lomkit\Rest\Concerns\Resource\DisableAuthorizations;
    
    // ...
}

Relationships

Because you may want to be able to control what models front end users are linking, Laravel Rest Api provides full control over relationship operations.

Attaching / Detaching

When working with relationships, Laravel Rest Api uses a simple policy method naming convention: attach{Model} / detach{Model}.

To illustrate this convention, let's assume your application has a Post resource and a Comment resource. If you would like to authorize which users can add comments to a post, you should define an attachComment method on your post model's policy class:

<?php

namespace App\Policies;

use App\Models\Comment;
use App\Models\User;
use App\Models\Post;
use Illuminate\Auth\Access\HandlesAuthorization;

class PostPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can attach a comment to a post.
     *
     * @param  \App\Models\User    $user
     * @param  \App\Models\Post    $post
     * @param  \App\Models\Comment $comment
     * @return mixed
     */
    public function attachComment(User $user, Post $post, Comment $comment)
    {
        return true;
    }

    /**
     * Determine whether the user can detach a comment from a post.
     *
     * @param  \App\Models\User    $user
     * @param  \App\Models\Post    $post
     * @param  \App\Models\Comment $comment
     * @return mixed
     */
    public function detachComment(User $user, Post $post, Comment $comment)
    {
        return true;
    }
}

Cache

In order to make Laravel Rest Api faster, authorizations are cached automatically.

Cache key

By default, caches is proper to each authenticated user and resource. If you want to change this behavior, please override the getCacheKey method in your resource:

class UserResource
{
    /**
     * Get the authorization cache key.
     *
     * @param RestRequest $request
     *
     * @return string
     */
    public function getAuthorizationCacheKey(RestRequest $request, string $identifier)
    {
        $class = Str::snake((new \ReflectionClass($this))->getShortName());

        return sprintf(
            'rest.authorization.%s.%s.%s',
            $class,
            $identifier,
            $request->user()?->getKey()
        );
    }
}

Cache time to live

Cache is by default persisted for 5 minutes, if you want to change this feature:

Globally

In your config/rest.php file, you can directly specify the number of minutes for the cache:

[
    // ...
    'authorizations' => [
        'cache'   => [
            'default' => 5 // Cache minutes by default
        ],
    ],
    // ...
]

Resource

If you want to adjust this in your resource, please add the cacheFor method in your resource:

class UserResource
{
    /**
     * Determine for how much time the cache should be keeped.
     *
     * @return \DateTimeInterface|\DateInterval|float|int|null
     */
    public function authorizationCacheFor()
    {
        return now()->addMinutes(5);
    }
}

Disable cache

Globally

If you want to disable it globally, change your config in the rest.php file

<?php

return [
    /*
    |--------------------------------------------------------------------------
    | Rest Authorizations
    |--------------------------------------------------------------------------
    |
    | This is the feature that automatically binds to policies to validate incoming requests.
    | Laravel Rest Api will validate each models searched / mutated / deleted to avoid leaks in your API.
    |
    */

    'authorizations' => [
        'cache'   => [
            'enabled' => false, // Set this to false
        ],
    ],
]

Resource

If you want to disable this feature for certain resources only, you can use the DisableAuthorizationsCache trait on your resource file:

UserResource.php
class UserResource extends Resource
{
    use \Lomkit\Rest\Concerns\Resource\DisableAuthorizationsCache;
    
    // ...
}

Copyright © 2024