Jim*_*sel 4 laravel single-page-application bearer-token vue.js laravel-passport
我一直在关注有关 Vue + Laravel 身份验证的教程,一切都已设置完毕,但随后教程转到将令牌存储在本地存储中。我读到这不是应该遵循的最佳实践,因为它更容易受到 XSS 攻击。
问题是很难找到关于在 cookie 中存储令牌的教程(特别是 Laravel + Vue)。任何人都可以帮助如何实现在 cookie 中存储令牌吗?
非常感谢任何可以提供帮助的人。
这是我当前的代码。
控制器
public function login(Request $request)
{
$http = new\GuzzleHttp\Client;
try {
$response = $http->post(config('services.passport.login_endpoint'), [
'form_params' => [
'grant_type' => 'password',
'client_id' => config('services.passport.client_id'),
'client_secret' => config('services.passport.client_secret'),
'username' => $request->username,
'password' => $request->password,
]
]);
return $response->getBody();
} catch (\GuzzleHttp\Exception\BadResponseException $e) {
if ($e->getCode() === 400) {
return response()->json('Invalid Request. Please enter a username or a password.', $e->getCode());
} else if ($e->getCode() === 401) {
return response()->json('Your credentials are incorrect. Please try again', $e->getCode());
}
return response()->json('Something went wrong on the server.', $e->getCode());
}
}
public function logout()
{
auth()->user()->tokens->each(function ($token, $key) {
$token->delete();
});
return response()->json('Logged out successfully', 200);
}
Run Code Online (Sandbox Code Playgroud)
API路线
Route::post('/login', 'AuthController@login');
Route::middleware('auth:api')->post('/logout', 'AuthController@logout');
Run Code Online (Sandbox Code Playgroud)
Vue 组件脚本
<script>
export default {
props: {
source: String,
},
data: () => ({
username: '',
password: '',
valid: false,
}),
methods: {
save() {
const { username, password } = this
axios
.post('api/login', { username, password })
.then(response => console.log(response))
.catch(error => console.log(error))
}
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
用于document.cookie = response.data.token在cookie中存储token
<script>
export default {
props: {
source: String,
},
data: () => ({
username: '',
password: '',
valid: false,
}),
methods: {
save() {
const { username, password } = this
axios
.post('api/login', { username, password })
.then(response => {
document.cookie = response.data.token
})
.catch(error => console.log(error))
}
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
https://www.w3schools.com/js/js_cookies.asp
要得到cookie
var token = document.cookie;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3749 次 |
| 最近记录: |