Our Work
200+ Enterprises across globally trust KTree for their Web & Mobile application Development needs.See What We Do
Updated today
You can refer the code here : https://github.com/KtreeOpenSource/Laravel_Authentication
In this article we will learn how to use laravel authentication passport package as authenticate service from other application. In this we have one laravel Web Application which provides the authentication services and another application which is basic PHP application which consumes the service provided by the Laravel Application.
You can download the source code for this example from github Link.
For this we are using passport package of laravel link.
Install the passport package refer link
Let's create the routes for logging in the laravel application after installing and configuring the passport package.
path:routes/api.php
Route::post('login', 'API\[email protected]');
Create a controller for the routes in Step 1.
On click get access token button we will call the login function.
path:app/Http/Controllers/API/UserController.php
public $successStatus = 200;
public function login(){
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')-> accessToken;//token generated
return response()->json(['success' => $success], $this-> successStatus);
}
else{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
Let's create the sample user login form for testing purpose and call the login function in the controller
path:public/widget.php
<form>
<h1>Laravel Authentication via Api</h1><br>
Email: <input name="email"><br>
Password: <input name="password"><br>
<input name="submit" type="submit" value="Submit"><br>
<div style="display:none" id='finalValue' ></div>
</form>
JavaScript:
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'http://xxxxxxxxx/api/login',
data: $('form').serialize(),
success: function (data) {
console.log('data is this ',data)
var token = data.success.token
if(token)
{
$('#finalValue').css('display','block');
$('#finalValue').text('Token from laravel is this '+token);
}
else
{
alert('Please provide proper credentials');
}
},
complete:function(res)
{
if(res.status != '200')
{
alert('Please provide proper credentials')
}
}
});
});
});
The user has to send the access token for subsequent requests otherwise he will be getting unauthorized code i.e. 401
Please Contact us if you have any Laravel Implementation requirements. Hire dedicated Laravel developers or Laravel Development services from KTree. KTree is Best offshore Laravel development company with extensive experience in building Laravel web applications and Laravel Plugins.
Request For Quote