简体   繁体   中英

Laravel token based User Authentication?

I have developed a web application using Laravel 5.1 and I am using Laravel Authentication for User Authorization and User Authentication.

And Now I want to Rest API for the same application with Token Based, stateless user Authorization.

Is there any way to do it directly with minimal modification in current code or using the same authorization for mobile applications but token based, if not then what is the quickest possible way to achieve this.

I have already checked oauth2-server-laravel But I don't think that, it will be useful in my case.

Thanks in advance!!!

You can use JWT-Auth for token based authentication on Laravel applications. Refer to the documentation on how to use it.

I am adding this answer just addition to above answer

First, I have added "tymon/jwt-auth": "0.5.*" to my composer.json file and ran composer update for pulling the JWT-Auth .

then, I have added check for Rest Request in my Authenticate Middleware and added JWT token validation for the request in authenticate Middleware

public function handle($request, Closure $next)
    {
        if($request->has('token')){
            $this->auth = JWTAuth::parseToken()->authenticate();
            return $next($request);
        }
        else{
            if ($this->auth->guest()) {
                if ($request->ajax()) {
                    return response('Unauthorized.', 401);
                } else {
                    return redirect()->guest('auth/login');
                }
            }
            return $next($request);
        }
    }

Then I have Modified Login and added check for Rest Request and Returning Rest API token for Rest Requests

if(isRestRequest){
            // grab credentials from the request
            $credentials = Input::only('email', 'password');

            try {
                // attempt to verify the credentials and create a token for the user
                if (! $token = JWTAuth::attempt($credentials)) {
                    return Response::json(['error' => 'invalid_credentials'], 401);
                }
            } catch (JWTException $e) {
                // something went wrong whilst attempting to encode the token
                return Response::json(['error' => 'could_not_create_token'], 500);
            }

            // all good so return the token
            return Response::json(compact('token'));


}

And rest everything is working as it was without much modification, even Auth::user() returns the User object with all the values.

Thumbs up for jwt-auth

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM