如何使用Laravel Passport访问令牌 [英] How to use Laravel Passport access tokens
问题描述
首先让我描述一下我要解决的问题.我有一个Laravel后端项目,我想转换成一个API,看起来Laravel Passport对此非常适合.因此,我在项目中安装了Laravel Passport.
我有一个客户端应用程序,它需要使用 axios 来使用此 API.我想要做的是使用我的用户名和密码向API发出发布请求,以获取此,但无法使其正常工作.>
如果需要,我会很乐意发布更多代码!
也许可以帮上忙.当我将访问令牌存储在前端应用程序中时,我还会附加标头
axios.defaults.headers.common ['Authorization'] =承载者" + token.data.access_token
您所有的axios请求都将使用此标头.
获取用户详细信息
Route :: middleware('auth:api')-> get('/user',函数(Request $ request){返回$ request-> user();});
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!
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();
});
这篇关于如何使用Laravel Passport访问令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!