我一直在学习关于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);
}API路由
Route::post('/login', 'AuthController@login');
Route::middleware('auth:api')->post('/logout', 'AuthController@logout');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>发布于 2020-01-03 10:44:03
使用document.cookie = response.data.token在cookie中存储令牌
<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>https://www.w3schools.com/js/js_cookies.asp
获得cookie
var token = document.cookie;发布于 2020-01-03 12:32:29
我认为最好的选择是使用refresh_token (与用户数据)作为服务器端cookie。并将token保存在vue存储中(您从token需要的一切都是用于用户视图的用户数据)。这个解决方案使XSS攻击成为不可能的。这意味着服务器端cookie块javascript来读取或写入此cookie。每次重新加载页面时,都需要使用“autoLogin”请求和refresh_token cookie进行重新授权(每个请求都自动使用cookie),例如:
vue商店,例如“auth.ts”或“auth.js”
/**
* Autologin user.
*
* @param commit
*/
async autologin({ commit }: any) {
try {
let { data } = await axios.post(`${endpoint}/${silentLogin}`)
setExpiresDateToken(data.accessToken)
commit('auth', {
token: data.accessToken,
idToken: data.idToken,
})
} catch (err) {
localStorage.removeItem('expires')
throw err
}
},router.ts或router.js (I user TypeScript)
/**
* Check if user access allows.
* @param to
* @param from
* @param next
* @returns {Promise<void>}
*/
const authGuard = async (to: any, from: any, next: any) => {
if (!store.getters['auth/isAuth']) {
try {
await store.dispatch('auth/autologin')
next()
} catch (e) {
next({ name: 'login' })
}
} else {
next()
}
}
const routes = [
{
path: '/list',
name: 'List',
component: () => import('@/views/DocumentsList'),
beforeEnter: authGuard,
}
]如果您使用Laravel路由器,这将是一种类似的方式。
https://stackoverflow.com/questions/59577057
复制相似问题