<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use App\User;
class AuthController extends Controller {
/**
* Create user
*
* @param [string] name
* @param [string] email
* @param [string] password
* @param [string] password_confirmation
* @return [string] message
*/
public function signup(Request $request) {
$request->validate([
'name' => 'required|string',
'email' => 'required|string|email|unique:users',
'password' => 'required|string|confirmed',
]);
$user = new User([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password),
]);
$user->save();
return response()->json(['message' => 'Successfully created user!'], 201);
}
/**
* Login user and create token
*
* @param [string] email
* @param [string] password
* @param [boolean] remember_me
* @return [string] access_token
* @return [string] token_type
* @return [string] expires_at
*/
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');
$token = $tokenResult->token;
if ($request->remember_me) {
$token->expires_at = Carbon::now()->addWeeks(1);
}
$token->save();
return response()->json([
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at
)->toDateTimeString(),
]);
}
/**
* Logout user (Revoke the token)
*
* @return [string] message
*/
public function logout(Request $request) {
$request->user()->token()->revoke();
return response()->json([
'message' => 'Successfully logged out',
]);
}
/**
* Get the authenticated User
*
* @return [json] user object
*/
public function user(Request $request) {
return response()->json($request->user());
}
}
C:\xampp\htdocs\auth\app\User.php
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable {
use Notifiable, HasApiTokens;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
C:\xampp\htdocs\auth\routes\api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::group([
'prefix' => 'auth'
], function () {
Route::post('login', 'AuthController@login');
Route::post('signup', 'AuthController@signup');
Route::group([
'middleware' => 'auth:api'
], function() {
Route::get('logout', 'AuthController@logout');
Route::get('user', 'AuthController@user');
});
});
[Laravel] Xác thực API với Laravel 5.6 Passport Authentication (Part1)
Chào mọi người, hôm nay mình lại quay lại đây, hôm nay mình sẽ hướng dẫn mọi người xác thực API bằng laravel passport
Trong các ứng dụng phần mềm hiện đại, các web API là không thể thiếu, có rất nhiều các mô hình ứng dụng sử dụng web API như mô hình server-to-server, hay mô hình SPA (Single Page Application). Trong quá trình phát triển các API, rất cần thiết phải bảo vệ dữ liệu khỏi những con mắt tò mò, điều này với các hệ thống truyền thống rất đơn giản còn với API thì sao? Laravel tạo ra một gói thư viện Passport giúp thực hiện xác thực trong API đơn giản đơn giản hơn, nó cung cấp đầy đủ OAuth2. Laravel Passport được xây dựng dựa trên League OAuth2 server được phát triển bởi Alex Bilbie Chúng ta bắt đầu luôn nhé
khi tải về mn nhớ tạo 1 file .env và chạy composer install và php artisan key:generate đây là những bước bình thường mình sẽ không nói sâu đến nữa
Install Laravel Passport Package
Chúng t a chỉ cần tải thư việc này về bằng composer nhé
composer require laravel/passport
Giống như hầu hết các package cho Laravel khác, chúng ta cần thêm service provider của Laravel Passport trong file config/app.php (việc thêm service provider cần được thực hiện sau khi package đã được tải về thông qua Composer)
Laravel\Passport\PassportServiceProvider::class,
Laravel Passport cung cấp sẵn một số migration class để tạo các bảng cần thiết để lưu trữ authorization codes, access tokens, refresh tokens, personal access tokens, thông tin về clients (danh sách các file migration có thể xem tại đây). Để cài đặt các bảng cần thiết cho Laravel Passport, chúng ta dùng lệnh sau:
php artisan migrate
Generate Key
Bước tiếp theo, chúng ta cần tạo encryption keys (được dùng khi tạo access tokens) và tạo các client liên quan đến Personal Access Grant và Password Grant
php artisan passport:install
sau khi chạy xong chúng ta thêm Laravel\Passport\HasApiTokens vào model 'App\user'. Trait này sẽ cung cấp 1 vài hepler cho phép kiểm tra token và phạm vi của người dùng
Passport Config
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use Notifiable, HasApiTokens;
}
Tiếp theo là gọi phương thức Passport::routes trong AuthServiceProvider, Phương thức này dùng để đăng ký những routes cần thiết để cho những vấn đề liên quan đến access tokens and revoke access tokens, clients, and personal access tokens
<?php
namespace App\Providers;
use Laravel\Passport\Passport;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
Passport::routes();
}
}
Cuối cùng là tại file config/auth.php, bạn nên chọn driver của api à passport, Điều này sẽ hướng ứng dụng của bạn sử dụng Passport's TokenGuard khi các thực yêu của của API
OK bài này hôm nay đến đây thôi, bài sau mình sẽ hướng dẫn làm
Part 2. Confirm account + notifications
Part 3. Generate avatar
Part 4. Reset Password
Part 5. Send Notifications with Queues on Redis nhé
Refer
TABLE OF CONTENTS
SUGGESTED ORGANIZATIONS
Related
More from Trần Văn Mỹ
Comments
Write
Preview
Hi bạn, cho mình hỏi chút
public function user(Request $request)
{
return response()->json($request->user());
}
được bạn ơi.
Cho mình hỏi, cái expired_at của token tại sao không có hiệu quả? mình thử add 5 phút, nhưng sau 5 phút thì dùng cái token đó vẫn access dc?
Api Signup
Api Login
Api Logout
41 70 167 9 11 67 14 21 50
12 min read 23586 14 2372 min read 921 9 0129 min read 3687 5 288 min read 3430 5 06
9 min read 1050 5 81615 min read 1031 7 2126 min read 650 8 0145 min read 310 1 04
Post Comment@vuongthai95Feb 15th, 2019 10:07 AM
hay bạn ơi! 0 |Reply@thangpmFeb 21st, 2019 11:05 AM
Cái hàm lấy thông tin user này mình ko hiểu lắm nhỉ, mình chạy api thì ko thấy trả về thông tin gì, Bạn giải thích giúp mình với. thank 0 |Reply@vunguyen10111995Feb 21st, 2019 4:20 PM
bạn đã đăng nhập để lấy được access_token chưa 0 |Reply@mih2t9xFeb 21st, 2019 4:37 PM
Vào tận đây để reply comment cơ à, chú có tâm quá =)) 0 |Reply@vunguyen10111995Feb 21st, 2019 4:38 PM
nó hiện lên discussions, ngày nào chả check cái đó =)) 0 |Reply@mih2t9xFeb 21st, 2019 4:39 PM
Bạn gửi cho mình xem cái postman bạn call api như nào 0 |Reply@thangpmFeb 21st, 2019 4:49 PM
get_token.png
get_user.png
Đây bạn ơi 0 |Reply@mih2t9xFeb 21st, 2019 4:53 PM
Bạn thử return 1 hay return ra cái gì đấy trong function user xem đã call được vào function đấy chưa 0 |Reply@thangpmFeb 21st, 2019 4:57 PM
ok.png
mình chỉ ko hiểu hàm này của bạn là ntn ? $request->user() 0 |Reply@vunguyen10111995Feb 21st, 2019 5:00 PM
bạn tích lại cái content-type:application/json rồi test lại xem 0 |Reply@thangpmFeb 21st, 2019 5:02 PM
vẫn thế bạn ơi 0 |Reply@vunguyen10111995Feb 21st, 2019 5:09 PM
ặc, mình test vẫn ok cơ mà nhỉ 0 |Reply@thangpmFeb 21st, 2019 5:10 PM
chắc sai code ở đâu đó rồi bạn. mình đang xem lại 0 |Reply@mih2t9xFeb 21st, 2019 5:03 PM
$request->user() dùng để truy xuất ra người dùng được xác thực hiện tại, cái này nó cũng giống như bạn dùng Auth::user() ấy 0 |Reply@thangpmFeb 21st, 2019 5:09 PM
Cảm ơn bạn nhiều nhé ^^ . để mình xem lại code xem 0 |Reply@thangpmFeb 22nd, 2019 10:25 AM
Tạo cái dự án mới thì lại chạy ngon rồi bạn ^^ 0 |Reply@thangpmFeb 22nd, 2019 10:31 AM
Untitled.png
ngồi gõ lại code của bạn mà gõ nhầm 0 |Reply@mih2t9xFeb 22nd, 2019 1:04 PM
ok bạn, phải gặp bug như thế thì bạn mới nâng cao trình độ được bạn à , chứ cứ làm theo bài viết của t thì cũng chỉ là học vẹt thôi ko đọng dk kiến thức gì cả đâu, 0 |Reply@thangpmFeb 22nd, 2019 4:00 PM
0 |Reply@luffybkchyproFeb 26th, 2019 7:23 AM
Hi Mỹ, cho mình hỏi chút. Khi mình test bằng Postman phần api user thì khi điền access token vào phần header thì báo lỗi Unauthenticated. Nhưng khi chuyển sang mục authorization rồi điền access token thì lại được. 0 |Reply@mih2t9xFeb 26th, 2019 11:02 AM
cái Key Authorization của bạn đang bị sai rồi kià , Bearer đằng sau làm gì có dấu . (chấm) bạn ơi 0 |Reply@lamtin222Jun 6th, 2019 9:06 AM