laravel get authorization bearer token
//get Authorization Bearer Token value
$token = $request->bearerToken();
laravel get authorization bearer token
//get Authorization Bearer Token value
$token = $request->bearerToken();
laravel 7 user registration using api post endpoint
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class AuthController extends Controller
{
public $loginAfterSignUp = true;
public function register(Request $request)
{
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password),
]);
$token = auth()->login($user);
return $this->respondWithToken($token);
}
public function login(Request $request)
{
$credentials = $request->only(['email', 'password']);
if (!$token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
public function getAuthUser(Request $request)
{
return response()->json(auth()->user());
}
public function logout()
{
auth()->logout();
return response()->json(['message'=>'Successfully logged out']);
}
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60
]);
}
}
laravel token authentication
# Database Preparation
// add api_token to users table
Schema::table('users', function ($table) {
$table->string('api_token', 80)->after('password')
->unique()
->nullable()
->default(null);
});
// Create token for existing users, code can also be added to registerController
$token = Str::random(60);
$user = User::find(1);
$user->api_token = hash('sha256', $token); // <- This will be used in client access
$user->save();
//config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token', // <- Add this entry
'provider' => 'users',
'hash' => false,
],
],
//routes/api.php
// Add "middleware('auth:api')" as below
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
//client access example (in Vue js)
axios.get('http://example.com/api/user',
{
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer '+ 'user-api-token'
}
}
)
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
Laravel api login
public function login(Request $request){
$fields = $request->validate([
'email'=>'required|string|email',
'password'=>'required|string'
]);
//Check email
$user= User::where('email', $fields['email'])->first();
//Check Password
if(!$user || !Hash::check($fields['password'], $user->password) ){
return response([
'message'=>'Invalid Credentials'
], 401);
}
$token = $user->createToken('myapptoken')->plainTextToken;
$response= [
'user' => $user,
'token'=> $token
];
return response($response, 201);
}
make authentication in laravel
composer require laravel/ui:^2.4
php artisan ui vue --auth
laravel api authentication
<?php
//custom made middleware for token generation and user authentication
//below code for Middleware file in /app/Http/Middleware
namespace App\Http\Middleware;
use Closure;
use \App\Admin;
use Illuminate\Support\Facades\Auth;
class ApiAuthenticate {
public function handle($request, Closure $next) {
$token = $request->bearerToken(); //set as Authorization -> Bearer token... in api requests
if ($token) {
$user = Admin::where('remember_token', $token)->first();
$request->request->add(['user' => $user]); //to fetch logged in user details in other apis
if ($user) {
return $next($request); //pass on the params to controller
} else {
return response()->json('Token expired.');
}
} else{
if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->get('remember'))) {
$remember_token = \Str::random(60);
$user = Auth::user();
$user->last_login = new \DateTime();
$user->remember_token = $remember_token;
$user->save();
$remember_token = Admin::where('id', Auth::user()->id)->value('remember_token');
//remember_token is fetched separately, as it set hidden in its Model
$data = ['remember_token'=>$remember_token]; //to use as Authorization -> Bearer remember_token, in other apis.
return response()->json($data);
}
}
return response()->json('Incorrect Credentials');
// return $next($request);
}
}
//pass below line in /routes/api.php
Route::post('leads', 'Api\UserController@index')->middleware('auth_api');
//use below code in Controller file
<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$data = ['user'=> 'data'];
return response()->json($data);
}
}
//also don't forget to pass this Middleware class in /app/Http/Kernel.php
protected $routeMiddleware = [
'auth_api' => \App\Http\Middleware\ApiAuthenticate::class,
];
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us