Sanctum Laravel 如何通过Token获取用户

How to get user by Token in Sanctum Laravel

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

我做了以下事情:

我的登录控制器

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
  },
}

我通过一些实验和阅读 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', $partner_token))->first();
    $user_id = $user_id->tokenable_id; // !!!THIS ID WE CAN USE TO GET DATA OF YOUR USER!!!
}
  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);
  }

如果您想验证令牌是否有效并获得相应的用户,Sanctum 库中有一个内置方法可以让您完全做到这一点:

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

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