Sessions in token based authentication

前端 未结 8 1104
轻奢々
轻奢々 2020-12-28 15:54

I am building an app in PHP Lumen which returns a token upon login. I am not sure how to proceed beyond this.

How am I supposed to maintain a session using these to

8条回答
  •  时光说笑
    2020-12-28 16:38

    Currently working on same type of application using lumen for API. Following 3 steps for Token based Authentication in Lumen with JWT:

    1. Create Token and return after login success

    public function login(Request $request) {
        $token = $this->jwt->attempt(['user_name' => $data['user_name'], 'password' => $data['password']]); //$token = $this->jwt->attempt($data); 
        if (!$token) {
            $response = array('success' => false, 'data' => null, 'detail' => array('message' => Messages::MSG_INVALID_USER, 'error' => array(Messages::MSG_INVALID_USER)));
            return response()->json($response);
        } else {
            $user = \Auth::setToken($token)->user();
            $data = array('token' => $token,'user_id' => $user->id);
            $response = array('success' => true, 'data' => $data, 'detail' => array('message' => Messages::MSG_SUCCESS, 'error' => null));
            return response()->json($response);
        }
    }
    

    2. Define middleware for token verification

    public function handle($request, Closure $next, $guard = null) {
        try {
            $token = $request->header('X-TOKEN');
            $user_id = $request->header('X-USER');
            $user = \Auth::setToken($token)->user();
            if ($user && $user->id == $user_id) {
                return $next($request);
            } else {
                $response = array('success' => false, 'data' => null, 'detail' => array('message' => Messages::MSG_ERR_INVALID_TOKEN, 'error' => Messages::MSG_ERR_INVALID_TOKEN));
                return response()->json($response);
            }
        } catch (Exception $ex) {
            $response = array('success' => false, 'data' => null, 'detail' => array('message' => Messages::MSG_ERROR_500, 'error' => array($ex)));
            return response()->json($response);
        }
    }
    

    3. Store token in localstorage or in cookies

    localStorage.setItem("Token", JSON.stringify(TokenData));
    TokenData = JSON.parse(localStorage.getItem("Token"));
    

    or

    $.cookie('Token', JSON.stringify(TokenData), {expires: 1, path: '/'});
    TokenData = JSON.parse($.cookie("Token"));
    

    4. Send token with every request in headers

    Request with custom headers

    $.ajax({
        url: 'foo/bar',
        headers: { 'X-TOKEN': TokenData.Token ,'X-USER': TokenData.UserId}
    });
    

    Headers to every request

    $.ajaxSetup({
            headers: { 'X-TOKEN': TokenData.Token ,'X-USER': TokenData.UserId}
        });
    

    Hope it'll help.

    Note: Add some checks and data validations while reading data from localstorage or cookies .

提交回复
热议问题