I am made an App with Laravel 9 back-end and ReactJS front-end and get a 401 unauthorized error even I am successfully logged-in in to my App.
Code is in api.php router and looks like below:
Route::post('/userdata', [AppHttpControllersProfileController::class, 'userData'])->middleware('auth')->name('userdata');
And here is a ProfileController:
<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;
use IlluminateSupportStr;
use IlluminateFoundationAuthAccessAuthorizesRequests;
use IlluminateFoundationBusDispatchesJobs;
use IlluminateFoundationValidationValidatesRequests;
class ProfileController extends Controller
{
private $apiToken;
public function __construct()
{
$this->apiToken = uniqid(base64_encode(Str::random(40)));
$this->middleware('auth');
}
/**
* Get the user's profile.
*
* @param Request $request
* @return Response
*/
public function userData(Request $request)
{
$user = Auth::user();
var_dump($user);
return "";
}
}
Purpose of this controller is to get logged-in users details for ReactJS GUI.
And also here is a code in AuthController.php which make user logged-in:
public function login(Request $request){
//User check
if(Auth::attempt(['email' => $request->email, 'password' => $request->password, 'is_active' => 1])){
$user = Auth::user();
if($user->email_verified_at !== NULL){
if (DB::table('domains')
->select('domain', 'valid_before')
->where('domain', $user->domain)
->whereDate('valid_before_at', '<=', Carbon::now())
->count()){
return response()->json([
'success' => false,
'data' => 'Username and password do not match or domain subscription is not valid or expired!'
], 200);
} else {
// Login and "remember" the given user...
Auth::login($user, true);
//Setting login response
$success['token'] = $this->apiToken;
$success['name'] = $user->name;
return response()->json([
'success' => true,
'data' => $success
], 200);
}
} else {
return response()->json([
'success' => false,
'data' => 'Please Verify Email!'
], 200);
}
} else {
//$success['success'] = false;
return response()->json([
'success' => false,
'data' => 'Username and password do not match or domain subscription is not valid or expired!'
], 200);
}
}
Also if anyone wants to see whole source codes of am App there re publically here in my GIT repos:
https://bitbucket.i4ware.fi/projects/LOG/repos/login-form/browse?at=refs%2Fheads%2Fmatti_0006
https://bitbucket.i4ware.fi/projects/SAAS/repos/saas-app/browse?at=refs%2Fheads%2Fmatti_0008