【问题标题】:Send token by React通过 React 发送令牌
【发布时间】:2021-10-16 05:21:25
【问题描述】:

我写了这个控制器的方法

public function login(Request $request)
{
    $attr = $request->validate([
        'email' => 'required|string|email',
        'password' => 'required|string|min:6'
    ]);

    if (!Auth::attempt($attr)) {
        return $this->error('Credentials not match', 401);
    }

    return response()->json([
       'access_token' => auth()->user()->createToken('auth_token')->plainTextToken,
       'token_type' => 'Bearer',
    ]);
}

它是返回令牌。但是我怎样才能将这个令牌用于其他请求呢?所以我用 React 写了这段代码 instance.js

import axios from 'axios'
let instance = axios.create({
    baseURL: 'http://localhost:8000',
    withCredentials: true,
    headers: {
        'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json',
    }
});

export default instance;

Login.js(函数句柄提交)

const handleSubmit = (event) => {
    event.preventDefault();
    instance.post('/api/auth/login', {
            email: emailRef.current.value,
            password: passwordRef.current.value
        
    }).then(res => {

        instance.get('/api/me').then((response) => {
            console.log(response);
        }
        )

    })

}

我发现 withCredentials: true 解决了这个问题并自动在 header 中设置 cookie 的信息。但是当我尝试向 /api/me 发送请求时,我的状态为 401。你能帮帮我吗?

【问题讨论】:

    标签: reactjs jwt authorization token laravel-sanctum


    【解决方案1】:

    我不知道您的系统,但是在您通过身份验证后,在 /api/auth/login 上,您不会将令牌传递给 api/me

    我认为你必须尝试类似:

    instance.post('/api/auth/login', {
        email: emailRef.current.value,
        password: passwordRef.current.value
    
    }).then(res => {
        let yourToken  = res.data.access_token; 
        instance.get('/api/me', {
            headers: {
                'Authorization': 'bearer ' + yourToken
            }}).then((response) => {
                console.log(response);
            });
    })
    

    如果您需要通过您的应用程序保存和共享您的令牌,您可以使用Context API

    【讨论】:

    • 状态 401。问题是我们发送了例如 109|VWRqnwlu4n4pA0bOIAcEUTxpM8okqNG3E6hMjjhn 的令牌,而它应该是 bearer |VWRqnwlu4n4pA0bOIAcEUTxpM8okqNG3E6hMjjhn。 Bur问题更大。我必须在所有请求中保存令牌以便我们/如果我想发送请求,我不会一直登录。
    • 也许你应该使用 Context API 来保存你的令牌。请参阅:reactjs.org/docs/context.htmlmedium.com/geekculture/…
    • 我知道,我可以使用 Context、Redux、localStorage 等,但它不安全。我读到最好的方法是使用 http-only cookie,但我不知道该怎么做
    • 我认为隐藏 JWT 是安全的并不是一个好主意。你不应该隐藏它。但是...您必须在您的 API 中验证它的签名以保护您的系统免受 JWT 劫持... http-only with cookie 是另一种方法,但我不知道这是否是最好的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-27
    • 2014-08-06
    相关资源
    最近更新 更多