laravel-docs-ru/sanctum.md at 9.x · russsiq/laravel-docs-ru · GitHub

Введение

Laravel Sanctum предлагает легковесную систему аутентификации для SPA (одностраничных приложений), мобильных приложений и простых API на основе токенов. Sanctum позволяет каждому пользователю вашего приложения создавать несколько токенов API для своей учетной записи.

2 : loggin in

Now we can log-in. Once again the HandleCors middleware will do its magic, and then the EnsureFrontEndRequestsAreStateful Middleware will (as its long name implies) make sure the request creates and uses a new session. This middleware will only be triggered if the domain name of your SPA is listed in the SANCTUM_STATEFUL_DOMAINS variable of your .env file, so make sure it’s correctly configured.

If everything works, a new session will be created and the corresponding cookie will be returned.

Actually signing in

Hopefully you get what’s going on in our Vuex store. Let’s hook this up so we can actually enter some credentials and get authenticated.

Update your views/SignIn.vue component with the following.

This hooks up our email and password fields to the component data, and then adds a submit event handler to the overall form. Once invoked, our form handler dispatches the signIn action from our store and does everything we spoke about in the last section.

Add some actions

Let’s update the store/auth.js file and add some actions. Don’t forget to import axios at the top!

Add some vuex state

I’ll prefix this with, *why are we using Vuex? *Well, since we want to hold an overall authenticated ‘state’ in our client, using a state management library like Vuex makes sense here. It’ll also allow us to easily check within any component if we’re authenticated or not (e.g. our navigation).

Похожее:  starcraft 2 – купить ключ – Торговая площадка игр – магазин аккаунтов и ключей!

First, create a store/auth.js file with the following.

Authentication with laravel/ui

Yup, we still need our standard authentication controllers, and with Laravel 7, these are tucked away in the laravel/ui package.

First get the laravel/ui package installed.

composer requirelaravel/ui

Then generate the authentication scaffolding (we’re just using Bootstrap here).

php artisanuibootstrap--auth

And finally compile assets, so we have some styling on our authentication pages.

npm install&& npm rundev

We don’t actually need this, but it helps if you still want to use standard web authentication for your project, and use Vue components in Laravel that make requests authenticated endpoints.

Change the session driver

In .env, update your session driver to use something other than file. The cookie option will work fine for now.

SESSION_DRIVER=cookie

Configure cors

Laravel 7 ships with the fruitcake/laravel-cors package. Head over to your config/cors.php config file and update the paths to look like this:

'paths'=>[

'api/*',

'/login',

'/logout',

'/sanctum/csrf-cookie'

],

Because we’re potentially going to be making requests from another domain, we’re making sure that as well as our API endpoints, we’re also allowing cross-origin requests to /login and /logout, as well as the special /sanctum/csrf-cookie endpoint (more on this later).

You’ll also want to set the supports_credentials option to true.

'supports_credentials'=>true

Configure sanctum

Open up the config/sanctum.php file and take a look. It’s crucial that we set the stateful key to contain a list of domains that we’re accepting authenticated requests from.

'stateful'=>explode(',', env('SANCTUM_STATEFUL_DOMAINS','localhost,127.0.0.1')),

Luckily for us, localhost is already in there, so we’re good to go. You will need to change this when deploying to production, so adding SANCTUM_STATEFUL_DOMAINS to your .env file with a comma separated list of allowed domains is a great idea.

I tend to add this anyway, since it sets my .env file with a reference to what I should be changing in production.

SANCTUM_STATEFUL_DOMAINS=localhost

Create a sign in page

Create a new file, views/SignIn.vue with a simple sign in form.

Now add this page component to the router. I’ve removed the /about page here because we don’t need it.

importVuefrom'vue'

importVueRouterfrom'vue-router'

importHomefrom'../views/Home.vue'

importSignInfrom'../views/SignIn.vue'

Vue.use(VueRouter)

constroutes= [

{

path:'/',

name:'Home',

component:Home

},

{

path:'/signin',

name:'SignIn',

component:SignIn

}

]

constrouter=newVueRouter({

mode:'history',

base:process.env.BASE_URL,

routes

})

exportdefaultrouter

Head over to /signin in the browser and you’ll see your beautifully crafted work.

Features of vue router

  • Nested Routes
  • Route params, query
  • Dynamic Routes Matching
  • Links with automatic active CSS classes
  • and many more

Let’s install vue-router

npm install vue-router

Now, Create Components For Login and Register.

Create a File inside resources/js/components folder name with Login.vue .

resources/js/components/Login.vue

Further knowledge

Naturally, the Laravel documentation for Sanctum gives you a good reference for installing and setting up.

Prefer screencasts? I’ve published two courses on using Sanctum with Nuxt and Vue.js.

Laravel Sanctum with Nuxt

Laravel Sanctum with Vue

Gut the home component

Clear our the views/Home.vue component, so you just have a plain homepage.

How laravel sanctum works

Before we start blindly mashing away without an understanding of what’s happening behind the scenes, let’s run over how Sanctum works.

Install vue cli and create a project

If you don’t already have the Vue CLI installed, it’s simple:

npm install-g@vue/cli

Then create a new project.

vue createtestingsanctumclient

Project setup

Let’s set up a Laravel project and install the Sanctum package.

The command above generates your Laravel project skeleton. This may take a while depending on your internet connection.

Next, cd into your project root and run the following command:

Output:

Now that we’ve installed sanctum, we need to configure and migrate files by running the following command:

Output:

With the sanctum files published, let’s now set up our database by editing the .env file contents as follows:

Now let’s proceed and create our database on a MySQL server by running the following command in the command line:

Output:

In front of mysql>, run the SQL commmand below to create a sanctum database:

Output:

Let’s now proceed to migrate our application as shown below:

Output:

You will notice that the personal_tokens table is generated. This is important to note because we’ll need it later on in the article.

Refresh the page

And check your Vue devtools. It now appears you’re unauthenticated, but you’re not. Our session cookie is still set, so any further requests we make to our API will be successful.

To get around losing our state, let’s make sure that we’re always requesting an authentication check when our app first runs.

Update main.js to dispatch the me Vuex action before the Vue app is created.

store.dispatch('auth/me').then(()=>{

newVue({

router,

store,

render:h=>h(App)

}).$mount('#app')

})

*Now *refresh the page and check your Vue devtools (remember, you might need to click ‘load state’ again). Your state should show you’re authenticated.

It’s time to update the navigation to reflect this.

Signing out

Because we’re already authenticated, and Laravel knows who we are, making a request to sign out is pretty easy. This process will invalidate our session, so the cookie we’re automatically sending to our API will no longer be valid.

Again, in App.vue.

Step 2: configure database detail

open .env and update database detail

Step 4: migrate database

php artisan migrate

Read Also:  Firebase Push Notification Laravel Tutorial

Step 5: install laravel sanctum

You can find documentation on the Official  Laravel   Website.

composer require laravel/sanctum

The whole process

So here’s a diagram of what happens when your SPA authenticates to your backend :

It’s a little dense, but let’s see what happens with each step :

Things to know before you start

Most of this is in the docs, but it’s really important so I’ll summarize here :

Tweak axios

Before we make these requests, we’ll need to set a base URL for our API (notice these are not included in the requests we have right now) and also enable the withCredentials option.

Hop on over to main.js and add those.

What is vue router?

Vue Router helps link between the browser’s URL / History and Vue’s components allowing for certain paths to render whatever view is associated with it.

Why laravel sanctum?

Here are some advantages of Sanctum😎:

  1. It is lightweight because it uses Laravel’s built-in cookie-based session authentication service.

  2. It supports mobile application authentication.

  3. It solves two basic problems:

Now🥰, Let’s start coding!🎉🎊✨

Step 1: Create a Laravel application.

You can use the laravel command or via the Composer package manager as follows:

Авторизация частных каналов вещания

Если вашему SPA необходимо аутентифицировать трансляцию по частным каналам или каналам присутствия, то вы должны вызвать метод Broadcast::routes в файле routes/api.php вашего приложения:

Аутентификация spa

Во-вторых, Sanctum существует для того, чтобы предложить простой способ аутентификации одностраничных приложений (SPA), которым необходимо взаимодействовать с API на базе Laravel. Эти SPA могут существовать в том же репозитории, что и ваше приложение Laravel, или могут быть полностью отдельным репозиторием, например SPA, созданным с помощью Vue CLI.

Для этой функции Sanctum не использует никакие токены. Вместо этого Sanctum использует встроенные в Laravel службы аутентификации сеанса на основе файлов cookie. Это обеспечивает преимущества защиты CSRF, аутентификации сеанса, а также защищает от утечки учетных данных аутентификации через XSS.

{tip} Совершенно нормально использовать Sanctum только для аутентификации токена API или только для аутентификации SPA. Тот факт, что вы используете Sanctum, не означает, что вы обязаны использовать обе функции, которые он предлагает.

Вы можете установить Laravel Sanctum через Composer:

composer require laravel/sanctum

Затем вы должны опубликовать файлы конфигурации и миграции Sanctum с помощью команды Artisan vendor:publish. Файл конфигурации sanctum будет помещен в ваш каталог config:

php artisan vendor:publish --provider="LaravelSanctumSanctumServiceProvider"

Наконец, вы должны запустить миграцию вашей базы данных. Sanctum создаст одну таблицу базы данных, в которой будут храниться токены API:

php artisan migrate

Аутентификация мобильного приложения

Вы также можете использовать токены Sanctum для аутентификации запросов вашего мобильного приложения к вашему API. Процесс аутентификации запросов мобильного приложения аналогичен аутентификации запросов стороннего API; однако, есть небольшие различия в том, как вы будете выдавать токены API.

Аутентификация токена api

{tip} Вы не должны использовать токены API для аутентификации собственного SPA. Вместо этого используйте функционал аутентификации SPA Sanctum.

Вход в систему

После того, как защита от CSRF была инициализирована, вы должны сделать POST-запрос к маршруту /login вашего приложения Laravel. Этот маршрут /login может быть реализован вручную или с использованием пакета безголовой аутентификации, такого как Laravel Fortify.

Выдача токенов api мобильного приложения

Для начала создайте маршрут, который принимает электронную почту / имя пользователя, пароль и имя устройства, а затем обменивает эти учетные данные на новый токен Sanctum. «Имя устройства», присвоенное этой конечной точке, предназначено для информационных целей и может иметь любое желаемое значение. В общем, значение имени устройства должно быть именем, которое узнает пользователь, например «iPhone 12 Nuno».

Как правило, вы делаете запрос к конечной точке токена с экрана «входа в систему» вашего мобильного приложения. Конечная точка вернет токен API в виде простого текста, который затем может быть сохранен на мобильном устройстве и использован для выполнения дополнительных API-запросов:

Когда мобильное приложение использует токен для запроса API к вашему приложению, оно должно передать токен в заголовке Authorization как Bearer-токен.

{tip} При выдаче токенов для мобильного приложения вы также можете указать полномочия токена.

Защита маршрутов api мобильного приложения

Как ранее было задокументировано, вы можете защитить маршруты так, чтобы все входящие запросы аутентифицировались, назначив маршрутам охранника аутентификации sanctum:

Защита от csrf

Для аутентификации вашего SPA страница «входа» вашего SPA должна сначала сделать запрос к конечной точке /sanctum/csrf-cookie для инициализации защиты от CSRF для приложения:

Как это работает

Laravel Sanctum существует для решения двух отдельных задач. Давайте обсудим каждую из них, прежде чем углубиться в изучение пакета.

Краткая информация о токенах api

Во-первых, Sanctum – это простой пакет, который вы можете использовать для выдачи токенов API своим пользователям без осложнений с OAuth. Этот функционал вдохновлен GitHub и другими приложениями, которые выдают «токены личного доступа». Например, представьте, что в «настройках учетной записи» вашего приложения есть экран, на котором пользователь может сгенерировать токен API для своей учетной записи.

Настройка миграции

Если вы не собираетесь использовать миграции Sanctum по умолчанию, то вам следует вызвать метод Sanctum::ignoreMigrations в методе register поставщика AppProvidersAppServiceProvider. Вы можете экспортировать миграции по умолчанию, выполнив следующую команду: php artisan vendor:publish –tag=sanctum-migrations

Настройка собственных доменов

Во-первых, вы должны настроить, из каких доменов ваш SPA будет делать запросы. Вы можете настроить эти домены с помощью параметра конфигурации stateful в файле конфигурации sanctum. Этот параметр конфигурации определяет, какие домены будут поддерживать аутентификацию ” с отслеживанием состояния ” с использованием файлов cookie сеанса Laravel при выполнении запросов к вашему API.

{note} Если вы обращаетесь к своему приложению через URL-адрес, который включает порт (127.0.0.1:8000), вы должны убедиться, что вы указали номер порта вместе с доменом.

Переопределение моделей по умолчанию

Хотя обычно это не требуется, но вы можете расширить модель PersonalAccessToken, используемую внутри Sanctum:

Затем, вы можете указать Sanctum использовать вашу пользовательскую модель с помощью метода usePersonalAccessTokenModel, предоставленного Sanctum. Как правило, вызов этого метода осуществляется в методе boot одного из поставщиков служб вашего приложения:

Полномочия токена

Sanctum позволяет вам назначать «полномочия» токенам. Полномочия служат той же цели, что и «права доступа» OAuth Scopes. Вы можете передать массив, содержащий строковые ключи полномочий, в качестве второго аргумента методу createToken:

При обработке входящего запроса, аутентифицированного Sanctum, вы можете определить, обладает ли токен указанными полномочиями, используя метод tokenCan:

Тестирование

Во время тестирования метод Sanctum::actingAs может использоваться для аутентификации пользователя и указания, какие полномочия должны быть предоставлены его токену:

Если вы хотите предоставить токену все полномочия, то вы должны указать * в списке полномочий метода actingAs:

To recap

  1. We’ve installed Laravel, obviously.
  2. We have our normal authentication controllers pulled in from laravel/ui, because we’re going to be making requests to them from our client.
  3. Sanctum is installed, configured, and we’re allowing authenticated requests from localhost.
  4. We can make cross-origin requests to /login, /logout and /sanctum/csrf-cookie.

Step 7: setup frontend

When we generated our frontend code earlier using  php artisan ui vue , an example component was generated under  resources/js/components/ExampleComponent.vue. Let’s create other components for Login, Register, and Dashboard Page.

Conclusion

Wow! 😎You’re great to go with Sanctum👍

I know somewhere along the article must’ve been overwhelming for some of us, so guess what🤩?I made the entire code for this article open-source on Github here . Do well to check it out for further clarifications(P . S: I have some extra resources and endpoints there too🤫).

I am open to contributions, comments, questions and further discussions. Thanks for reading🤝

Отзыв токенов

Вы можете «отозвать» токены, удалив их из своей базы данных, используя отношение tokens трейта LaravelSanctumHasApiTokens:

Отзыв токенов api мобильного приложения

Чтобы пользователи могли отзывать токены API, выданные для мобильных устройств, вы можете перечислить их по имени вместе с кнопкой «Отозвать» в разделе «Настройки учетной записи» пользовательского интерфейса веб-приложения, например. Когда пользователь нажимает кнопку «Отозвать», вы можете удалить токен из базы данных.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *