I have created a laravel api with passport autentication. I have the following front-end login that works perpectly.
<script type="text/javascript">
$("#loginfrm").on("submit", function(event){
event.preventDefault();
var username = $("#username").val();
var password = $("#password").val();
var dcookie = document.cookie;
$.ajax({
type: "POST",
url: "http://api-auth.test/api/auth/login",
headers: {
"X-CSRF-TOKEN" : '{{ csrf_token() }}',
"Authorization": "Bearer " + "{{ Cookie::get('laravel_token') }}",
},
data:{
"_token": "{{ csrf_token() }}",
"username": username,
"password": password
},
complete: function (data) {
if (data.responseJSON["authstat"] == "Authorized")
{
window.location.href = "http://api-auth.test/employees";
}
else
{
alert(data.responseJSON["authstat"]);
}
}
});
});
</script>
And my API routes/api.php
:
Route::prefix('auth')->group(function(){
Route::post('/register', 'AuthController@register');
Route::post('/login', 'AuthController@login');
});
Consuming my own api:
My problem is, when my application redirects to "http://api-auth.test/employees"
, the page is not really authenticated. Below is my routes/web.php
:
Route::get('/inbox', function () {
return view('pages.employees');
});
Then I tried to encapsulate my route as what I have search here in stackoverflow:
Route::group(['middleware' => 'auth:api'], function () {
Route::get('/inbox', function () {
return view('pages.employees');
});
});
And it returns an error:
Symfony\Component\Routing\Exception\RouteNotFoundException
Route [login] not defined.
I found out that the error occur in Middleware/Authenticate.php
and I dont know what to do with it.
protected function redirectTo($request)
{
if (!($request->expectsJson())) {
return route('login');
}
}
I just want to display the list of Employee when it redirects to http://api-auth.test/employees
for testing purposes. here is my EmployeeController
:
public function index()
{
$employee = Employee::all();
return response()->json([
"success" => true,
"message" => "Employee List",
"data" => $employee
]);
}
Any help? Thanks.
You need to Apply "auth" middleware not "auth:api"