Laravel 5.3 Rest API login


Laravel 5.3 Rest API login

我在尝试使用Laravel 5.3创建rest API登录时遇到了麻烦。我创建了一个扩展User的学生模型,它有电子邮件和密码(在迁移中)。

这是守卫(我已将提供者更改为学生)

  'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'api' => [
        'driver' => 'token',
        'provider' => 'students'
    ],
],

这是提供商

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App'User::class,
    ],
    'students' => [
        'driver' => 'eloquent',
        'model' => App'Student::class,
    ],

    'teachers' => [
        'driver' => 'eloquent',
        'model' => App'Teacher::class,
    ],
],

我想做一个登录API (rest)使用学生的凭据。如果登录成功,服务器将返回学生的个人信息。我搜索了很多laracast,但没有发现类似的东西。新版本有很多变化。所以我很困惑。

学生登录功能

public function login(Request $request){
    if (Auth::check(['email' => $request->email, 'password' => $request->password])) {
        //$student = Student::where('email',$request->email)->first();
        $student = Auth::user();
        $student->api_token = str_random(60);
        $student->save();
        return response([
            'status' => Response::HTTP_OK,
            'response_time' => microtime(true) - LARAVEL_START,
            'student' => $student
        ],Response::HTTP_OK);
    }
    return response([
        'status' => Response::HTTP_BAD_REQUEST,
        'response_time' => microtime(true) - LARAVEL_START,
        'error' => 'Wrong email or password',
        'request' => $request->all()
    ],Response::HTTP_BAD_REQUEST);
}

在这种情况下,Auth::check()方法和Auth::validate()方法都不起作用。有什么问题吗?如何实现rest api的登录?

我对你有点问题…

我使用了一个层次特征,覆盖了一些方法,并创建了一个ApiController用于handdel ever response

请查看:

<?php
namespace App'Http'Controllers'Api;
use Illuminate'Routing'Controller as BaseController;
class ApiController extends BaseController
{
    protected $statusCode=200;
    public function getStatusCode()
    {
        return $this->statusCode;
    }
    public function setStatusCode($code) 
    {
        $this->statusCode = $code;
        return $this;
    }
    public function respondNotFound($message = 'Not Found')
    {
        return $this->setStatusCode(404)->respondWithError($message);
    }
    public function respondInternalError($message = 'Internal Error')
    {
        return $this->setStatusCode(500)->respondWithError($message);
    }
    public function respondUnathourize($message = 'Login Failed username or password doesnt match')
    {
        return $this->setStatusCode(401)->respondWithError($message);
    }
    public function respond($data, $headers=[])
    {
        return response()->json($data,$this->getStatusCode(), $headers);
    }
    private function respondWithError($message) 
    {
        return $this->respond([
            'error' => [
                'message'=>$message,
                'status_code' => $this->getStatusCode()
            ],
        ]);
    }
}

这是我的登录控制器(authenticateconcontroller。php)

<?php
namespace App'Http'Controllers'Api;
use Illuminate'Foundation'Auth'AuthenticatesUsers;
use Illuminate'Http'Request;
use Illuminate'Foundation'Validation'ValidatesRequests;
class AuthenticateController extends ApiController
{
    use AuthenticatesUsers,ValidatesRequests;
    public function login(Request $request)
    {        
        $this->validateLogin($request);
        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if ($lockedOut = $this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);
            return $this->sendLockoutResponse($request);
        }
        $credentials = $this->credentials($request);
        if ($this->guard()->attempt($credentials, $request->has('remember'))) {
            return $this->sendLoginResponse($request);
        }
        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        if (! $lockedOut) {
            $this->incrementLoginAttempts($request);
        }
        return $this->sendFailedLoginResponse($request);
    }
    protected function sendLoginResponse(Request $request)
    {               
        $this->clearLoginAttempts($request);
        $this->setApiKey();
        return $this->respond([
           'data'=>$this->guard()->user() 
        ]);
    }
    /**
     * Get the failed login response instance.
     * @overide
     */
    protected function sendFailedLoginResponse()
    {
        return $this->respondUnathourize();
    }    
    private function setApiKey()
    {
        $user = $this->guard()->user();
        $user->api_token = sha1(date("Y-m-d H:i:s").$user->name);
        $user->save();
    }
}

希望能有所帮助

欢呼

亨德拉