te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>reactjs - Laravel 11 web api when we use HttpOnly then cookies aren't being sent with that request - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - Laravel 11 web api when we use HttpOnly then cookies aren't being sent with that request - Stack Overflow

programmeradmin4浏览0评论

I have an app using Laravel 11 (Sanctum) as the web API and React as the frontend. Authentication works with HttpOnly cookies, but after login, /user returns 401 Unauthorized.

Axios is set with withCredentials: true CORS is configured with supports_credentials: true CSRF cookie is fetched before login (/sanctum/csrf-cookie) Here’s my code: [Include relevant snippets]

How can I ensure the session cookie is sent and recognized correctly?

import axios from "axios";

const apiClient = axios.create({
    baseURL: import.meta.env.VITE_API_URL,
    withCredentials: true,
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest'
    }
});

apiClient.interceptors.request.use(config => {
    const token = document.cookie.replace(/(?:(?:^|.*;\s*)XSRF-TOKEN\s*=\s*([^;]*).*$)|^.*$/, '$1');
    if (token) {
        config.headers['X-XSRF-TOKEN'] = token;
    }
    return config;
});

export default apiClient;
import axios from 'axios';
import apiClient from './apiClient';

const api = axios.create({
    baseURL: import.meta.env.VITE_API_URL,
    withCredentials: true, 
    headers: {
        'Accept': 'application/json',
    }
});

export const fetchUser = async () => {
    try {
      const response = await apiClient.get('/user');
      if (response.status === 200) {
          return response.data;
      }
  } catch (error) {
      if (error.response?.status === 401) { 
          throw new Error('Authentication failed');
      }    
      throw error;
  }
};

Login.js

  const handleLogin = async (e) => {
    e.preventDefault();
    try {        await apiClient.get('/sanctum/csrf-cookie');      
        const loginResponse = await apiClient.post('/login', {
            email,
            password,
            ip  
        });        
            const userData = await fetchUser();

            if (userData) {             
                setAuth(true);
                navigate('/dashboard');
            }
        }
    } catch (error) {     
        setError(error.response?.data?.message || "Login failed. Please try again.");
    }
};

AuthController.php

public function login(Request $request): JsonResponse
{
    try {
        $validated = $request->validate([
            'email' => ['required', 'string', 'email'],
            'password' => ['required', 'string'],
        ]);         

        $user = User::where('email', $validated['email'])->first();

        if (!$user || !Hash::check($validated['password'], $user->password)) {              
            return response()->json(['message' => 'Invalid credentials.'], 401);
        }        

        // Generate token
        $token = $user->createToken('auth_token')->plainTextToken;        

        $cookie = cookie(
            'auth_token',
            $token,
            60,
            '/',
            null,    // domain (keep null for localhost)
            false,    // secure (false for HTTP)
            true,     // httpOnly
            false,
            'Lax'     // sameSite (use Lax/Strict for HTTP)
        );      
        return response()->json([
            'message' => 'Login successful.',
            'user' => $user->only(['id', 'name', 'email'])
        ])->cookie($cookie);

    } catch (\Exception $e) {           
        return response()->json(['message' => 'Internal server error'], 500);
    }
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论