如何在Sanctum Laravel中通过令牌获取用户

xpcnnkqh  于 2023-04-13  发布在  其他
关注(0)|答案(4)|浏览(216)

我在POST请求体中向服务器传递用户的Token。我需要找出这个Token属于哪个用户。在laravel/sanctum文档中,我发现只有将Token设置为“Authorization”才能做到这一点:“Bearer****”头。但这不是我的情况,我需要在POST主体中传递它。有没有办法这样做?

gmxoilav

gmxoilav1#

如果你想验证一个token是否有效并获取相应的用户,Sanctum库中有一个内置的方法可以让你做到这一点:

// Fetch the associated token Model
$token = \Laravel\Sanctum\PersonalAccessToken::findToken($yourToken);

// Get the assigned user
$user = $token->tokenable;
vh0rcniy

vh0rcniy2#

我通过做一些实验和阅读Sanctum的源代码找到了一个解决方案。用户的数据可以通过POST数据中的令牌以这种方式获得:

$post_data = $request->all();
if (isset($post_data['user_token'])) {
    [$id, $user_token] = explode('|', $post_data['user_token'], 2);
    $token_data = DB::table('personal_access_tokens')->where('token', hash('sha256', $user_token))->first();
    $user_id = $token_data->tokenable_id; // !!!THIS ID WE CAN USE TO GET DATA OF YOUR USER!!!
}
watbbzwu

watbbzwu3#

我做了以下工作:
我的登录控制器

class LoginController extends Controller
{
    use ApiResponser;

    public function __invoke(Request $request)
    {
        // attempting login
        if(!auth()->attempt($request->only('email', 'password'))) {
            return $this->error(401, 'Credentials not match' );
        }

        // Delete old tokens
        auth()->user()->tokens()->delete();

        // Succesfull login and new token created.
        return $this->success([
            'token' => auth()->user()->createToken('API Token', auth()->user()->abilities())->plainTextToken
        ]);
    }

所以你有清楚的洞察力,我下一步在我的ApiResponser是只为漂亮的状态消息。

namespace App\Traits;

use Illuminate\Http\JsonResponse;

trait ApiResponser
{
    /**
     * Returns a succesfull response
     * @param $data
     * @param string|null $message
     * @param int $code
     * @return JsonResponse
     */
    protected function success($data, string $message = null, int $code = 200): JsonResponse
    {
        return response()->json([
            'status' => 'Success',
            'message' => $message,
            'data' => $data
        ], $code);
    }

    /**
     * Return an error JSON response.
     *
     * @param  string  $message
     * @param  int  $code
     * @param  array|string|null  $data
     * @return JsonResponse
     */
    protected function error( int $code, string $message = null, $data = null): JsonResponse
    {
        return response()->json([
            'status' => 'Error',
            'message' => $message,
            'data' => $data
        ], $code);
    }

}

我收到以下JSON

{
    "status": "Success",
    "message": null,
    "data": {
        "token": "156|mmEL7OV24DO79W5E6IdAXiQaHa8BCXK6271hLE3m"
    }
}

我有一个nuxtJS项目,在我的登录组件中,我有以下内容

methods: {
    login(e) {
      e.preventDefault()
      this.$auth
        .loginWith('laravelSanctum', {
          data: this.form,
        })
        .then((resp) => {
          this.$auth.strategy.token.set(resp.data.data.token)
          this.$axios.setToken(resp.data.data.token, 'Bearer')
        })
        .catch((e) => {
          // eslint-disable-next-line no-console
          console.log('Failed Logging In')
        })
    },
  },

最后在我的VueX用户商店里

export const actions = {
  async fetchAllUsers(state, payload = false) {
    state.commit('SET_BUSY', true)
    this.$axios.setToken(this.$auth.strategy.token.get(), 'Bearer')
    const response = await this.$axios('users', {
      headers,
      params: payload,
    })
    console.log(response.data)
    state.commit('GET_USERS', response.data.data.data)
    state.commit('SET_SEARCH', response.data.data.search)
    state.commit('SET_FILTERS', response.data.data.filters)
    state.commit('SET_BUSY', false)
  },
  async createUser(state, payload) {
    this.$axios.setToken(this.$auth.strategy.token.get(), 'Bearer')
    const response = await this.$axios.post('user', payload, {
      headers,
    })
    state.commit('ADD_USER', response.data.data)
    return response
  },
}
zte4gxcn

zte4gxcn4#

if($request->has('token')){

         [$id, $token] = explode('|', $request->input('token'), 2);
         $token_data = DB::table('personal_access_tokens')->where('token', hash('sha256', $token))->first();
         
         dd($token_data);
  }

相关问题