How to work with API tokens in Laravel Jetstream
Complete guide to configuring Sanctum in Laravel Jetstream

Laravel Jetstream and Sanctum: Configuring the Authentication API

Старт! Честный VDS/VPS, на котором «Лунная База» живет уже 20+ лет

Задумываетесь о том, чтобы поднять свой pet-проект, сайт клиента или настроить окружение для разработки? Уже пора подумать, где арендовать железо.

Лунная База хостится на FirstVDS более 20 лет. Мыслей о том, чтобы перебраться на другой хостинг, не было ни разу (хотя опыт работы с другими вариантами, конечно, есть).

Бывали разные ситуации, но они бывают на любом железе. Главное, что нужно понять: здесь нет маркетинговой шелухи и сказок про «мы всё сделаем за вас». Если вы берете VDS — вам дают полный root, возможность накатить любую ОС и не лезут в ваши конфиги.

Если в саппорт написать с вопросом по вашему коду и получить ответ: «Читайте документацию и разбирайтесь сами» или «Обратитесь к профильному специалисту» — это не повод обижаться. Это повод углубить свои знания в DevOps и сайтостроении! Бегите от тех, кто пообещает: «Мы всё чиним и настраиваем абсолютно бесплатно!». Никто никогда не работает «по доброте душевной» в ущерб себе, а бесплатный сыр в администрировании обычно заканчивается сломанной базой данных.

Что по факту: Гибкое масштабирование ядер и RAM, экономия по сравнению с физическими серверами и адекватная панель ispmanager, если она вам нужна.



Introduction

Jetstream includes first-party integration with Laravel Sanctum. Laravel Sanctum provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token based APIs. Sanctum allows each user of your application to generate multiple API tokens for their account. These tokens may be granted abilities / permissions which specify which actions the tokens are allowed to perform.

API token management in Laravel Jetstream with Sanctum

By default, the API token creation panel may be accessed using the "API" link of the top-right user profile dropdown menu. From this screen, users may create Sanctum API tokens that have various permissions.

Sanctum Documentation
For more information on Sanctum and to learn how to issue requests to a Sanctum authenticated API, please consult the official Sanctum documentation.

Enabling API Support

If your application will be offering an API to third-parties, you must enable Jetstream's API feature. To do so, you should uncomment the relevant entry in the features configuration option of the config/jetstream.php configuration file:

'features' => [
    Features::profilePhotos(),
    Features::api(),
    Features::teams(),
],

Defining Permissions

The permissions available to API tokens are defined using the Jetstream::permissions method within your application's JetstreamServiceProvider. Permissions are just simple strings. Once they have been defined they may be assigned to an API token:

Jetstream::defaultApiTokenPermissions(['read']);

Jetstream::permissions([
    'create',
    'read',
    'update',
    'delete',
]);

The defaultApiTokenPermissions method may be used to specify which permissions should be selected by default when creating a new API token. Of course, a user may uncheck a default permission before creating the token.

Authorizing Incoming Requests

Every request made to your Jetstream application, even to authenticated routes within your routes/web.php file, will be associated with a Sanctum token object. You may determine if the associated token has a given permission using the tokenCan method provided by the Laravel\Sanctum\HasApiTokens trait. This trait is automatically applied to your application's App\Models\User model during Jetstream's installation:

$request->user()->tokenCan('read');

First-Party UI Initiated Requests

When a user makes a request to a route within your routes/web.php file, the request will typically be authenticated by Sanctum through a cookie based web guard. Since the user is making a first-party request through the application UI in this scenario, the tokenCan method will always return true.

At first, this behavior may seem strange; however, it is convenient to be able to always assume an API token is available and can be inspected via the tokenCan method. This means that within your application's authorizations policies you may always call this method without fear that there is no token associated with the request.

Original Web-site:
https://jetstream.laravel.com/1.x/features/api.html

Самый честный хостинг за 20+ лет существования Лунной Базы

Задумываешься о том, чтобы поднять свой сайт в Интернете? Уже пора подумать о том, какой хостинг выбрать?

Лунная База хостится 20+ лет на firstDVS. При этом, мыслей о том, чтобы перебраться на другой хостинг не было. (Но, при этом есть опыт работы с другими вариантами.)

Бывали с firstDVS разные ситуации, но, они бывают на всех хостингах. Единственное, что тут важно понять, - это то, что никто ничего тебе не будет впаривать... Но, и работать за тебя тоже никто не станет. Если в саппорт ответили: «Читайте по ссылке и разбирайтесь сами...» или вообще «Обратитесь за помощью к специалисту», - это повод углубить свои знания в области сайтостроения, а не бежать к тем, что пообещают: «Мы всё чиним и всё делаем за своих клиентов абсолютно бесплатно!» Никто никогда ничего ни за кого "по доброте душевной" не делал, не делает и не будет делать!

Старт! MoonВase — A Hot Start on the Internet
Старт! MoonВase — A Hot Start on the Internet
Старт! Menu