Laravel Sanctum 登录后未认证

huangapple go评论72阅读模式
英文:

Laravel Sanctum Unauthenticated after login

问题

我正在尝试为SPA(React)与Sanctum设置身份验证。

每当我成功登录,然后尝试访问auth:sanctum中间件中的路由时,它会返回401未经授权的错误。

以下是我的URL:

SPA:localhost:3000

后端:https://local-erp.XXX.com/

以下是我的配置文件:

sanctum.php:

'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
    '%s%s',
    'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1,https://local-erp.XXX.com',
    Sanctum::currentApplicationUrlWithPort()
))),

kernel.php:

protected $middlewareGroups = [
    'web' => [
        \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,
    ],

    'api' => [
        \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
        \Illuminate\Routing\Middleware\ThrottleRequests::class . ':api',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];

.env:

SESSION_DOMAIN:.localhost

我还尝试过*.localhostlocalhost

这是我的LoginController:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Service\Ldap;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    protected $redirectTo = RouteServiceProvider::HOME;

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    public function username()
    {
        return 'username';
    }

    protected function credentials(Request $request)
    {
        return [
            'sAMAccountName' => $request->username,
            'password' => $request->password
        ];
    }
}

这是我的查询:

axios.get("https://local-erp.XXX.com/sanctum/csrf-cookie").then(response => {
    axios.post("https://local-erp.XXX.com/login", {username: "xxx", password: "xxxx"})
})

这两者都返回204 OK状态码。

然后,当我发送这个查询:

const querytest = () => {
    axios.get('https://local-erp.XXX.com/api/users/5/holiday-balance')
}

它返回{"message":"Unauthenticated."}

我知道有很多关于这个问题的帖子,但我尝试了所有我能找到的东西,没有解决我的问题。

值得注意的是,我实际上正在将一个Laravel Blade应用程序移动到一个独立的SPA和后端应用程序中。目前,身份验证是通过LDAP工作的(必须继续工作)。

非常感谢您的帮助!

英文:

I'm trying to setup auth for SPA (react) with sanctum.

Whenever I login successfully, and then, try to get a route that is in auth:sanctum middleware, it return me 401 Unauthenticated.

These are my urls :

SPA : localhost:3000

Backend : https://local-erp.XXX.com/

These are my config files :

sanctum.php :

    &#39;stateful&#39; =&gt; explode(&#39;,&#39;, env(&#39;SANCTUM_STATEFUL_DOMAINS&#39;, sprintf(
        &#39;%s%s&#39;,
        &#39;localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1,https://local-erp.XXX.com&#39;,
        Sanctum::currentApplicationUrlWithPort()
    ))),

kernel.php:

    protected $middlewareGroups = [
        &#39;web&#39; =&gt; [
            \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,
        ],

        &#39;api&#39; =&gt; [
            \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            \Illuminate\Routing\Middleware\ThrottleRequests::class . &#39;:api&#39;,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

.env :

SESSION_DOMAIN:.localhost

I also tried *.localhost, localhost

This is my LoginController :

&lt;?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Service\Ldap;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this-&gt;middleware(&#39;guest&#39;)-&gt;except(&#39;logout&#39;);
    }

    public function username()
    {
        return &#39;username&#39;;
    }

    protected function credentials(Request $request)
    {
        return [
            &#39;sAMAccountName&#39; =&gt; $request-&gt;username,
            &#39;password&#39; =&gt; $request-&gt;password
        ];
    }
}

This is my queries :

axios.get(&quot;https://local-erp.XXX.com/sanctum/csrf-cookie&quot;).then(response =&gt; {
      axios.post(&quot;https://local-erp.XXX.com/login&quot;,  {username: &quot;xxx&quot;, password: &quot;xxxx&quot;})
    })

which returns both 204 OK Status Code.

Then when I send this :

const querytest = () =&gt; {
    axios.get(&#39;https://local-erp.XXX.com/api/users/5/holiday-balance&#39;)
  }

It returns {&quot;message&quot;:&quot;Unauthenticated.&quot;}

I know there is a lot of post about this, but I tried everything I could find and nothing fixed my problem.

It might be good to know, I'm actually moving a laravel blade app into a separate spa and back application. Currently, auth worked with ldap (which must still work).

Any help would be greatly appreciated!

答案1

得分: 0

经过多次测试,我发现不可能使用不同的域名。

在我的情况下,即使我使用子域名,也不能使用相同的域名,所以我的解决方案是使用API令牌进行身份验证。
它非常有效,并被用作RESTful API。

英文:

After severals test, I found it was not possible to use different domains names.

In my case I couldn't use the same one, even if I used subdomains, so my solution was to auth with API token.
It works like a charm and is used as an RESTFUL API.

huangapple
  • 本文由 发表于 2023年7月17日 16:31:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76702700.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定