Laravel Sanctum API identify user that is trying to post a Note - laravel

So I'm new to Laravel and I've made Login/Signup page to work with React SPA and Laravel Backend, the problem is i don't know now to post to database only for that user, I mean to add a note for that user, How can i do that, how the backend will know that, what is method around that?

Laravel Sanctum provides middlewares to authenticate the requests coming to a route. For that, first, you should validate the user-credentials and generate the token as specified here in the doucmentation.
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
Route::post('/sanctum/token', function (Request $request) {
$request->validate([
'email' => 'required|email',
'password' => 'required',
'device_name' => 'required',
]);
$user = User::where('email', $request->email)->first();
if (! $user || ! Hash::check($request->password, $user->password)) {
throw ValidationException::withMessages([
'email' => ['The provided credentials are incorrect.'],
]);
}
return $user->createToken($request->device_name)->plainTextToken;
});
This route validates the user credentials and creates a token. You should include this token in the subsequent requests.
Then protect your routes by including the auth:sanctum middleware.
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Now the $request->user() should return the current authenticated user.
Also read about SPA-Authentication.
https://laravel.com/docs/8.x/sanctum#spa-authentication

Related

Laravel rest api (santum) for mobile application

I have created a REST API with LARAVEL SANCTUM. I have tested api on postman and it works as expected but when mobile developer uses it on ionic app, it returns for login "TOKEN MISMATCH".
Here is my API route
Route::post('/register', [ApiController::class, 'register']);
Route::post('/login', [ApiController::class, 'login']);
Here is the ApiController for login
public function login(Request $request){
$fields = $request->validate([
'email' => 'required|string|email|max:255',
'password' => 'required|string|min:8'
]);
//validate login parameters
//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;
//return $user->createToken($request->device_name)->plainTextToken;
$response = [
'user' => $user,
'token' =>$token,
];
return response($response, 201);
}
EndPoint: https://findajob.ng/api/login
Email:johndeo1#gmail.com
Password: 12345678
This might not be a problem from backend, but in other-hand, if everything work in postman, you might try to:
Change support_credentials in config\cors to true.
Add withCredential header to front-end.

Laravel Sanctum - getting 401 on auth:sanctum with token returned after login

I have the following login method:
public function index(Request $request)
{
$request->validate([
'email' => 'required|email',
'password' => 'required',
'device_name' => 'required'
]);
$user = User::where('email', $request->email)->first();
if (! $user || ! Hash::check($request->password, $user->password)) {
throw ValidationException::withMessages([
'email' => ['The provided credentials are incorrect.'],
]);
}
return response([
'user' => $user,
'session_token' => $user->createToken($request->device_name)->plainTextToken,
], 201);
}
This method is working and returning token is a format similar to this:
5|5lR3o7vEzlm6iOieKxTW2pco1msKLN0WHb0Ozxv2relwIB4eJetyPnADOu6Dp0griYY7U1YZJEAqk6Ct
When I try to use a route behind auth:sanctum with that token I am getting
401 - "message": "Unauthenticated."
I am using the latest Laravel 7. Configuration:
.env
APP_URL=http://localhost:9099
SANCTUM_STATEFUL_DOMAINS=http://localhost:9099
cors.php
'paths' => ['api/v1/*'],
I am using Insomnia for API testing. The login method works and also any route that doesn't use auth:sanctum middleware.
Any idea what am I doing wrong here?
Assuming you are running the server on port 9099 try setting your .env file to:
SESSION_DOMAIN=http://localhost
SANCTUM_STATEFUL_DOMAINS=http://localhost:9099
SANCTUM_STATEFUL_DOMAINS should be set the same as the url in your browser
I had my expiration set as null and I kept getting 401 errors. When I changed it to 60*24*30 it works.

Allow only authenticated users to access API routes

I want to allow only authenticated users to access some API routes. I use the default Laravel authentication system. After the default login, I want to be able to access a route, but I get the "Unauthenticated" message.
So, after login, I am redirect to the home route which uses the HomeComponent file. Here, using axios, I am making a call to the step API route where I am trying to get the id of the authenticated user, but instead I receive an error message. What am I doing wrong?
api.php
Route::middleware('auth:api')->group(function () {
Route::get('application/step', ['as' => 'application.step', 'uses' => 'ApplicationController#step']);
});
ApplicationController.php
public function step() {
print_r(auth()->user());
die('---');
// code to get authenticated user step
return json_encode(array('step' => 7));
}
LoginController.php
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
$user = User::where('email', $request->email)->firstOrFail();
if ($user && !$user->isAdmin()) {
if (Auth::attempt(['email' => $request->email, 'password' => $request->password], true)) {
$token = $user->createToken('TokenName')->token;
$token->save();
return redirect()->route('home');
}
else {
return back()->withInput($request->only('email'));
}
}
return back()->withInput($request->only('email'))->withErrors(['denied' => 'You are not allowed to access this page.']);
}
HomeComponent.vue
...
getStep() {
axios.get("/api/application/step")
.then((response) => {
this.step = response.data.step;
})
.catch((err) => {
console.log('Cannot get step', err);
});
}
auth:api middleware only work with Passport. This auth:api middleware check valid access token.
And I think you are not using passport for login
composer require laravel/passport
In your case you can only use auth middleware instead auth:api

How to use web and api guards at the same time in Laravel?

I have build application with two parts: RESTful part for mobiles and web.
How can I use web/api guards at the same time? That I can register users with stadart web form, and accept request like as Restful?
Protect whatever routes are for your api with auth:api middleware
Route::group(['middleware' => ['auth:api']], function(){
//protected routes for API
});
We must make sure that your users table has an api_token column:
php artisan make:migration alter_users_table_add_api_token_column
Then inside of the up function:
Schema::table('users', function($table){
$table->string('api_token', 60)->unique(); //this must be 60 characters
});
Finally in your App\Http\Controllers\Auth\RegisterController, modify the create file to add your api_token
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'api_token' => str_random(60) //add this
]);
}
Now request to the auth:api protected routes will need to contain an api_token in their payload.

How to redirect after auth in Laravel?

When I authorize in Laravel 5.3 I redirect to /home page.
I tried to change this on: protected $redirectTo = '/order'; in file LoginController.
But It does not work, I am redirected on home still.
In my UserController.php , I hope email and passwords are the things you use for user signin.
public function userSignIn(Request $request)
{
$this->validate($request,[
'email' => 'required|email',
'password' => 'required'
]);
if(Auth::attempt(['email'=>$request['email'],'password'=>$request['password']])){
return redirect()->route('order');
}
return redirect()->back();
}
You must have a route for order in your route.php file.

Resources