gpt4 book ai didi

How do I configure laravel sanctum to authorize other domains and that can be consumed by NuxtJS(如何配置LARLAVEL DISATOM以授权其他域,并且可以由NuxtJS使用)

转载 作者:bug小助手 更新时间:2023-10-25 22:13:04 26 4
gpt4 key购买 nike



I have a Nuxt application as a client and a laravel 9 API, this api is using Laravel-Sanctum, I am having problems connecting my Nuxt application with Laravel because the endpoint that is managing sanctum tells me that I am not authorized, both front and back domains are different, is there a configuration that I am skipping and that is why it does not work? here I share my code with you:

我有一个Nuxt应用程序作为客户端和一个laravel 9 API,此API使用的是Laravel-Sanctom,我在将Nuxt应用程序与Laravel连接时遇到问题,因为管理SAMENTM的端点告诉我我未获授权,前域和后域不同,是否存在我跳过的配置,这就是它不起作用的原因?在这里,我与大家分享我的代码:


config/cors.php

配置/cors.php


<?php

return [

'paths' => ['api/*', 'login', 'logout', 'sanctum/csrf-cookie', 'api'],

'allowed_methods' => ['*'],

'allowed_origins' => ['*'],

'allowed_origins_patterns' => [],

'allowed_headers' => ['*'],

'exposed_headers' => [],

'max_age' => 0,

'supports_credentials' => true,

];

config/sanctum.php

CONFIG/SAINTUR.php


<?php

use Laravel\Sanctum\Sanctum;

return [

'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1,https://mango-grass-0b3b8cd10.3.azurestaticapps.net/',
Sanctum::currentApplicationUrlWithPort()
))),

// 'guard' => ['web'],

'expiration' => null,

'middleware' => [
'verify_csrf_token' => App\Http\Middleware\VerifyCsrfToken::class,
'encrypt_cookies' => App\Http\Middleware\EncryptCookies::class,
],

];

config/session.php

配置/会话.php


<?php

use Illuminate\Support\Str;

return [

'driver' => env('SESSION_DRIVER', 'file'),

'lifetime' => env('SESSION_LIFETIME', 120),

'expire_on_close' => false,

'encrypt' => false,

'files' => storage_path('framework/sessions'),

'connection' => env('SESSION_CONNECTION'),

'table' => 'sessions',

'store' => env('SESSION_STORE'),

'lottery' => [2, 100],

'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
),

'path' => '/',

'domain' => env('SESSION_DOMAIN'),

'secure' => env('SESSION_SECURE_COOKIE'),

'http_only' => true,

'same_site' => 'lax',

];

config/kernel.php

Config/kernel.php


<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;
use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;

class Kernel extends HttpKernel
{
protected $middleware = [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Illuminate\Http\Middleware\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\Fruitcake\Cors\HandleCors::class,
];

protected $middlewareGroups = [
'web' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
// \Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Fruitcake\Cors\HandleCors::class,
],

'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:60,1',
\Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Fruitcake\Cors\HandleCors::class,
],
];

protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \App\Http\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
}

nuxt.config.js

Nuxt.config.js


auth: {
redirect: {
home: '/',
logout: '/login',
login: '/login',
},
plugins: [
'~/plugins/auth.js',
{ src: '~/plugins/sweetalert2.js', mode: 'client' },
{ src: '~/plugins/VueDebounce.js' },
],
strategies: {
laravelSanctum: {
provider: 'laravel/sanctum',
url: backendUrl,
endpoints: {
login: {
url: '/api/login',
},
logout: {
url: '/api/logout',
},
},
},
},
},

login.vue

Login.vue


const handleSubmit = async () => {
if (email.value === '' || password === '') {
Swal.fire({
title: '¡Información!',
text: '¡Existen campos obligatorios vacíos.!',
icon: 'info',
confirmButtonText: 'Aceptar',
})
} else {
loaderButton.value = true
await $auth
.loginWith('laravelSanctum', {
data: { email: email.value, password: password.value },
})
.then((response) => {
backendService.value.getMe().then((responseMe) => {
localStorage.setItem('UserName', responseMe.name)
localStorage.setItem('UserEmail', responseMe.email)
localStorage.setItem('token', response.data.token)
getPermissionRol(responseMe.permission)
router.push('/')
})
})
.catch((error) => {
if (error.code === 'ECONNREFUSED') {
Swal.fire({
title: '¡Error!',
text: 'No se puede conectar con el servidor. Verifique su conexión a internet o inténtelo más tarde.',
icon: 'error',
confirmButtonText: 'Aceptar',
})
} else if (error.request && error.request.message) {
Swal.fire({
title: '¡Error!',
text: error.request.message,
icon: 'error',
confirmButtonText: 'Aceptar',
})
} else {
Swal.fire({
title: '¡Error!',
text: '¡Error!',
icon: 'error',
confirmButtonText: 'Aceptar',
})
}
})
.finally(() => {
loaderButton.value = false
})
}

I would appreciate your help please.

如果您能帮忙,我将不胜感激。


I followed the steps in the documentation about the sanctum configuration, I tried to put the values in the .env file and it didn't work either, it keeps sending me the error "419 unknown status" when I try to login.

我按照文档中的步骤进行了设置,我尝试在.env文件中输入这些值,但也不起作用,当我尝试登录时,它一直向我发送错误消息“419未知状态”。


更多回答
优秀答案推荐

set sanctumn.php :

设置staumn.php:


'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8080,::1',
Sanctum::currentApplicationUrlWithPort()
))),

then set env variable in .env file as given below:

然后在.env文件中设置env变量,如下所示:


FRONTEND_URL=http://localhost:3000
ROOT_URL=//127.0.0.1:8080
APP_URL=http://localhost
SESSION_DRIVER=cookie
SESSION_DOMAIN=.localhost

then run these commands in laravel project:

然后在laravel项目中运行以下命令:


php artisan config:clear && php artisan cache:clear && php artisan optimize && php artisan serve

then in your nuxt login.vue:

然后在您的nuxt登录.vue中:


async function validate() {

await useFetch("http://localhost:8080/sanctum/csrf-cookie", {
credentials: "include",
});

const token = useCookie('XSRF-TOKEN');

await useFetch("http://localhost:8080/api/login", {
credentials: "include",
method: "POST",
body: {
'email': 'email',
'password': 'password'
},
headers: {
'X-XSRF-TOKEN': token.value as string,
},
watch: false
})
// remaining codes...
}

更多回答

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com