问题
First let me describe the problem I want to solve. I have a Laravel backend project that I want to tranform into an API, and it looked like Laravel Passport was perfect for this. Therefore, I installed Laravel Passport into my project.
I have a client app which needs to use this API using axios. What I want to do is to make a post request with my username and password to the API to get an access token, and then use this access token to get or post relevant data. The access token is created by the following code
public function login()
{
if (Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')->accessToken;
return response()->json($success['token']);
// return response()->json(['success' => $success], 200);
} else {
return response()->json(['error' => 'Unauthorised'], 401);
}
}
and my app stores the access token. Am I correct in thinking that my app can now use this access token to gain access to the data of the user I made the login with? If so, how would I do that? I have tried using this, but I could not make it work.
I will gladly post more code if needed!
回答1:
Maybe this could help. when i store the access token on my frontend app i also attach the header
axios.defaults.headers.common['Authorization'] = "Bearer " + token.data.access_token
all your axios request will use this header.
getting user detail
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
来源:https://stackoverflow.com/questions/54201827/how-to-use-laravel-passport-access-tokens