dongranding3909
dongranding3909
2018-11-20 16:51

将授权用户从Laravel后端传递到React前端的最安全方式

已采纳

I am building a weather app with laravel(almost finished) and i decided to implement the frontend with react/redux/react-router and use laravel from api calls. The only thing that i decided to leave the same is my custom laravel auth implementation with routes and views. However, i struggle to find a secure way to pass my Auth::user object after login in order to store on redux. I have 2 options:

1) After login and before render the main jsx, to make an axios request to specific route in order to return the Auth::user like:

in routes.php

Route::post('/auth/user' ,function(){
   return response()->json(['user'=>auth()->user()]);
})->middleware('auth');

in js

axios.post('/auth/user').then((res)=>{console.log(res.data.user)}).catch((e)=>{console.log(e)})

2) pass Auth::user with blade, catch it with getAttribute, save it to redux and instantly remove from DOM:

<div id="app" data-usr="{{ auth()->user() }}"></div>

However neither of them seem to me like a secure way to pass this kind of data. Can anyone tell me his opinion about this or figure me with a better solution? Thanks a lot.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dongpu4141 dongpu4141 3年前

    Thankfully i found a solution with API TOKEN implementation built-in with Laravel. Also i destroy token after logout and recreate it in login, so nobody can use it with other services to collect data if he is not signed in

    点赞 评论 复制链接分享
  • doumi7854 doumi7854 3年前

    I would create a Class to represent the user with just the vital information I need to show on the front-end.

    So instead of passing auth->user() to the front, you can inject it into a decorator and generate a simpler user class with just the methods you wish to display.

    点赞 评论 复制链接分享