简体   繁体   English

如何通过API登录用户-Laravel 5.8?

[英]How to log user in via API - Laravel 5.8?

I'm using Laravel 5.8, with PHP 7.2. 我正在使用Laravel 5.8和PHP 7.2。

I need to adjust the way I did the Authentication. 我需要调整进行身份验证的方式。

before 之前

I used to log my users in via my local database from users table. 我曾经通过用户表通过本地数据库登录用户。

If the email+password match, I log them in. 如果电子邮件和密码匹配,我将其登录。

$email = strtolower(Input::get('email'));
$password = Input::get('password');

$dbAuth = Auth::attempt(array(
    'email' => $email,
    'password' => $password,
    'active' => 1
));

if ($dbAuth) {
    Session::put('user', Auth::user());
    return Redirect::to('/dashboard')->with('success', 'You have been successfully logged in.');

} else {
    return Redirect::to('/')->with('error', 'Username/Password Wrong')->with('email', $email)->withErrors($validator);
}

now 现在

Now I need to call /login API, that will return a token . 现在,我需要调用/login API,它将返回一个token I need to store that token into the local storage on my browser. 我需要将该令牌存储到浏览器的本地存储中。

I need to make sure my Auth::user() will work base on change. 我需要确保我的Auth::user()可以根据更改工作。

How do I start ? 我该如何开始?

Can someone please shed some lights ? 有人可以打点灯吗?

Use Laravel Passport And then you can do something like this 使用Laravel Passport然后您可以做类似的事情

public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|string|email',
            'password' => 'required|string',
            'remember_me' => 'boolean',
        ]);

        $credentials = request(['email', 'password']);

        if (!Auth::attempt($credentials)) {
            return response()->json([
                'message' => 'Unauthorized'
            ], 401);
        }
        $user = $request->user();

        $tokenResult = $user->createToken('Personal Access Token ' . str_random(10));

        $token = $tokenResult->token;

        if ($request->remember_me) {
            $token->expires_at = Carbon::now()->addWeeks(10);
        }

        $token->save();

        return response()->json([
            'access_token' => $tokenResult->accessToken,
            'token_type' => 'Bearer',
            'expires_at' => Carbon::parse(
                $tokenResult->token->expires_at)
                ->toDateTimeString(),
        ]);
    }

this will give you an access token to use in your following requests 这将为您提供一个访问令牌,可用于以下请求

Here's an example of a register controller method that uses Laravel Passport's createToken() method to generate a unique access token. 这是使用Laravel Passport的createToken()方法生成唯一访问令牌的register控制器方法的示例 You could use similar functionality to return this token when the user logs in. 您可以使用类似的功能在用户登录时返回此令牌。

public function register(Request $request)
{
    $validator = Validator::make($request->all(), [ 
        'name' => 'required', 
        'email' => 'required|email', 
        'password' => 'required', 
        'retype_password' => 'required|same:password', 
    ]);

    if ($validator->fails()) { 
        return response()->json($validator->errors(), Response::HTTP_FORBIDDEN);            
    }

    $user = User::firstOrCreate(
        ['email' => $request->email],
        ['name' => $request->name, 'password' => bcrypt($request->password)]
    ); 

    $response = [
        'token' => $user->createToken('MyApp')->accessToken
    ];

    return response()->json($response, Response::HTTP_CREATED);
}

You can use JWT 您可以使用JWT

Setup jwt after that you can use this code to login and return token : 之后设置jwt,您可以使用以下代码登录并返回令牌:

public function login() {
    /// validation 

    $credentials = request(['email', 'password']);
    if (!$token = auth('api')->attempt($credentials)) {
        return response()->json(['error' => 'Unauthorized'], 401);
    }
    return response()->json([
        'token' => $token, // Token
        'expires' => auth('api')->factory()->getTTL() * 60, // Expiration
    ]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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