我一直在网上寻找,但找不到任何方式。让我解释一下,我有一个API(流明上的Laravel护照),我用Postman测试过,我用oauth获得了访问令牌,一切都很好。现在,我有另一个Laravel应用程序,我想知道如何使用API保留所有身份验证内容。我已经看到很多实际上检索api_token的应用程序,它们使用'Auth :: user()-> where('api_token',$ token)'。但是我发现这是错误的,因为我不希望我的客户端访问数据库,我希望对数据库的每个请求都由API处理。有可能吗?
假设您要通过api登录laravel后端应用。确保安装了枪口。
Route(api):Route::POST('/login', 'AuthController@login')
控制器:AuthController.php
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|string',
]);
$http = new \GuzzleHttp\Client;
try {
$response = $http->post(config('services.passport.login_endpoint'), [
'form_params' => [
'grant_type' => 'password',
'client_id' => 'your client_id',
'client_secret' => 'your client_secret',
'username' => $request->email,
'password' => $request->password,
// 'scope' => '',
],
]);
return $response->getBody();
} catch (\GuzzleHttp\Exception\BadResponseException $e) {
if ($e->getCode() == 401) {
return response()->json(['message' => 'This action can\'t be perfomed at this time. Please try later.'], $e->getCode());
} else if ($e->getCode() == 400) {
return response()->json(['message' => 'These credentials do not match our records.'], $e->getCode());
}
return response()->json('Something went wrong on the server. Please try letar.', $e->getCode());
}
}
在您的前端应用程序中,例如vuejs,甚至使用vue组件的laravel。
<script>
export default ({
name: 'pages-authentication-login-v2',
metaInfo: {
title: 'Login'
},
state: {
token: localStorage.getItem('access_token'),
},
mutations: {
login(state, token) {
state.token = token
},
},
data: () => ({
form: new Form({
email: '',
password: '',
})
}),
methods: {
login(){
this.form.post('/api/login')
.then((response) =>{
const token = response.data.access_token
localStorage.setItem('access_token', token)
// console.log(response);
this.$router.push('/dashboard');
})
.catch((error)=>{
this.$toasted.error('Ooops! Something went wrong', {
icon : "warning",
theme: "bubble",
closeOnSwipe: true,
position: "top-right",
duration : 5000,
singleton: true,
})
});
},
}
})
</script>
让我知道您是否想了解更多。如果该答案有帮助,请加注并标记为答案将鼓励我们帮助像您这样的其他人。