You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native结合Laravel实现注册后会话创建及Token生成咨询

注册后生成Token并维护会话的实现方案

一、Laravel端:生成并返回认证Token

会话的核心是后端生成的认证Token,Laravel推荐用Sanctum(适合新手,配置简单)来实现API认证,步骤如下:

  1. 安装Sanctum依赖
composer require laravel/sanctum
  1. 发布配置文件与迁移文件
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
  1. 运行数据库迁移
php artisan migrate
  1. 在User模型中添加API Token支持
    修改app/Models/User.php,引入HasApiTokens trait:
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
    
    // 其他原有代码...
}
  1. 修改注册接口,生成并返回Token
    在你的注册控制器(比如RegisteredUserController)的store方法末尾,添加Token生成逻辑:
public function store(Request $request)
{
    // 原有表单验证、创建用户代码...
    
    // 为新用户生成认证Token
    $token = $user->createToken('auth_token')->plainTextToken;

    // 返回用户信息与Token
    return response()->json([
        'user' => $user,
        'access_token' => $token,
        'token_type' => 'Bearer'
    ]);
}

二、React Native端:存储Token并携带请求

React Native没有localStorage,需要用AsyncStorage来持久化存储Token,后续请求通过请求头携带Token完成身份验证:

  1. 安装AsyncStorage依赖
npm install @react-native-async-storage/async-storage
  1. 修改注册请求代码,存储Token
    更新你的axios请求逻辑,接收后端返回的Token并保存:
import AsyncStorage from '@react-native-async-storage/async-storage';

// ...原有代码
axios
  .post('http://10.0.2.2:8000/api/details', Data56)
  .then(async res => {
    // 存储Token到本地
    await AsyncStorage.setItem('token', res.data.access_token);
    // 跳转到首页,可携带用户信息而非原始表单数据
    props.navigation.navigate('Home_scrren', {data: res.data.user});
  })
  .catch(error => {
    alert(error.response?.data?.message || error.message);
  });
  1. 封装带Token的请求实例
    后续所有需要身份验证的API请求,都要携带Token,可封装axios实例简化操作:
import axios from 'axios';
import AsyncStorage from '@react-native-async-storage/async-storage';

const api = axios.create({
  baseURL: 'http://10.0.2.2:8000/api'
});

// 请求拦截器:自动在请求头添加Token
api.interceptors.request.use(async config => {
  const token = await AsyncStorage.getItem('token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

export default api;

总结

  • Laravel负责生成Token、验证Token合法性,是会话认证的核心;
  • React Native负责存储Token、在后续请求中携带Token,实现前端会话维持。

内容的提问来源于stack exchange,提问作者vivek kn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 20:25:17