Laravel-用户使用Laravel端点通过社交媒体帐户登录/注册

时间:2019-08-14 13:32:00

标签: angular laravel

我正在为应用程序使用Laravel 5.8和Angular 7。 1.发球:Laravel 5.8 2.客户:Angular 7

我已经在Laravel中创建了一个端点,用户可以按照以下所示的常规方式注册或登录:

     <?php
 namespace App\Http\Controllers;
 use Illuminate\Http\Request;
 use Illuminate\Support\Facades\Auth;
 use Tymon\JWTAuth\Exceptions\JWTException;
 use App\Permission;
 use App\Role;
 use App\User;
 use Validator;

 class ApiController extends Controller
 {

public $successStatus = 200;

 public function register(Request $request)
 {
    $validation = Validator::make($request->all(), [
        'name' => 'required',
        'email' => 'required|email|unique:users|max:255',
        'password' => 'required|confirmed|min:8|max:20',
    ]);
    if ($validation->fails()) {
        return response()->error('Validation failed', 422, $validation->errors());
    }
    $user = User::create([
        'name' => $request->name,
        'email' => $request->email,
        // 'password' => $request->password
        'password' => bcrypt($request->password)
    ]);
    // return response()->success($user, 'Registered');
    $token = auth()->login($user);

    return response()->json([
        'access_token' => $token,
        'token_type' => 'bearer',
        'expires_in' => auth()->factory()->getTTL() * 60
    ], 201);        
 } 

 public function login(Request $request)
 {
    $validator = Validator::make($request->all(), [
        'email' => 'required|string|email|max:255',
        'password'=> 'required'
    ]);

    $credentials = $request->only(['email', 'password']);
    $current_user = $request->email;

    try {
        // verify the credentials and create a token for the user
            if ($validator->fails()) 
            {
                return response()->json($validator->errors(), 422);
            }               
            if (!$token = auth()->attempt($credentials)) 
            {
                return response()->json(['error' => 'Invalid Credentials'], 400);
            }
        } 
        catch (JWTException $e) 
        {
            // something went wrong   
            return response()->error('Could not create token', 500);
        }   

     return response()->json([
     'access_token' => $token,
     'token_type' => 'bearer',
     'current_user' => $current_user,
     'expires_in' => auth()->factory()->getTTL() * 60
     ], 200);
  } 
 }

我正在使用jwtAuth

route.php

    // Route to register a user
Route::post('register', 'ApiController@register');
// Route to get a JWT via given credentials.
Route::post('login', 'ApiController@login');

现在的问题是,如何使用社交媒体创建用户登录/注册(Laravel后端)

  1. Goole
  2. Twitter
  3. Facebook

它将被Angular 7使用。

谢谢

1 个答案:

答案 0 :(得分:0)

[https://medium.com/techcompose/create-rest-api-in-laravel-with-authentication-using-passport-133a1678a876][1]

请检查此网址。 如果要在Laravel中使用rest-api,则应使用路由文件“ app / api.php”而不是route.php