Laravel passport ( can`t understand) - vue.js

I read a lot of articles and watched a lot of videos about Laravel passport but still can not understand some things.
I have an application which works with Laravel 5.5 + vueJs. All requests to the back-end are sent via axios. All my routes are located in api.php
Route::middleware('api')->group(function(){
Route::get('/prepare/', 'CompgenApiController#prepareDefault');
Route::post('/replace/', 'CompgenApiController#replaceImage');
Route::get('/replaceall/', 'CompgenApiController#replaceAllImages');
Route::get('/collage/', 'CompgenApiController#collage'); //#todo переделать на POST
Route::get('/generate/', 'CompgenApiController#generate');
Route::post('/upload/', 'CompgenApiController#userUpload');
Route::post('/reupload/', 'CompgenApiController#moderationReupload');
});
Also I have a VK bot that sends requests to the same routes.
At the moment I have some difficulties. For some routes, I need to check that the user is authorized (but this is an optional condition) and if it is true I need to write user id to the database. For me it was a surprise that
Auth :: check
returned false though I was authorized. After some searches I learned that the session that starts after authorization is not connected with the API and I was recommended to use Passport. I can not understand the following things
Do I need to use a passport if requests are sent from my application from vueJs?
How to register users? Do I have to issue my token for each new user?
How can I verify that the user is authorized?
In some cases I need to check that the user is authorized but if it is not so then do not interfere with the request. How can I do that?
Maybe in my case I do not need a passport at all?

Passport is an oAuth2 server implementation, essentially, it allows you to authenticate users by passing a token with each request. If you do not want to authenticate a user, then you do not need to pass the token and passport doesn't get involved.
In terms of a Laravel app, if you are consuming your API from your own frontend, you probably just want to use the implicit grant. Here's how you set that up:
1) Install passport and add it the PassportServiceProvider to config/app.php
2) php artisan migrate to setup the passport migrations
3) php artisan passport:install - to set up your oAuth server
4) In the User model add the Laravel\Passport\HasApiTokens trait, like so:
namespace App;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
// Other model methods
}
5) Setup the passport routes by adding the following to the boot method of your app\Providers\AuthServiceProviders.php:
\Laravel\Passport\Passport::routes();
6) Change your api driver in config/auth.php to token:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
That sets up passport, now all you need to do to allow your app to consume your api is to add the CreateFreshApiToken Middleware to web in app/Http/Kernel.php, which handles all the token logic:
'web' => [
// ..Other middleware...
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
Now all you need to do to protect a route is to use the auth:api middleware on that route:
Route::middleware('auth:api')->get('/profile','Api\UsersController#edit');
That should all work fine, but you'll also want to register a new user. All you do is add the auth routes as normal to web.php:
Route::post('/login', 'Auth\LoginController#login');
Route::post('/logout', 'Auth\LoginController#logout');
Route::post('/register', 'Auth\RegisterController#register');
You can then simply maks a post request to those routes and Laravel will handle all the token stuff for you.
That handles api routes that require authentication, however, you also mentioned that you want to check if a user is authenticated, but not necessarily lock the route, to do that you can simply use:
Auth::guard('api')->user();
Which will get the authenticated user, so you could do something like:
public function getGreeting(){
$user = Auth::guard('api')->user();
if($user !== null) {
return response()->json(["message" => "Hello {$user->name}"], 200);
}
return response()->json(["message" => "Hello Guest"], 200);
}
That's it. Hopefully, I've covered everything there.

Related

"Attempt to read property \"id\" on null", Create access token error with laravel passport, laravel 9, php 8.2.2

devs,
so I have been struggling with this problem for about 10 hours now, and I can't seem to find a solution online, worst is that I don't even know why it happens.
I am working on a project which uses PHP LARAVEL as the backend and I started writing the API for the flutter frontend to consume then I ran into this error while trying to test the API endpoint for registering and logging in.
The problem is the process fails with this error when I try to generate or create a token for the registered user or logged-in user.
Here a snapshot of my register function
public function store(Request $request)
{
$validated = Validator::make($request->all(),[
"email" => "required|email",
"password" => 'required',
"first_name"=> "required",
"last_name" => "required",
"phone_number" => 'required',
]);
if ($validated->fails()) {
return response()->json(['errors' => "Invalide credentials"], 403);
}
$user = User::create(
// [
// 'first_name' => $request->first_name,
// 'last_name'=> $request->last_name,
// 'email' => $request->email,
// 'password' => bcrypt($request->password),
// 'phone_number' => $request->phone_number,
// ]
$request->toArray()
);
Auth::guard('api')->check($user);
// $newUser = User::find($user->id);
$token = $user->createToken('authToken')->accessToken;
// return $token;
return response(['token' => $token, 'first_name'=>$user->first_name, 'email'=>$user->email ], 200);
}
The login and register functions all look the same at this point.
Error-causing code is :
$token = $user->createToken('authToken')->accessToken;
Please I am open to your suggestions, thanks.
I finally found a solution for this error and I believe it will help anyone out there with a similar problem.
The problem originates from the fact that your application is unable to asign a unique id to your client, remember your website or mobile app is a client to the backend with also(your mobile app or website) might have other users, so laravel passport will need to identify it with a unique id, below are some of the steps i used to fix this error.
First it originates because during the passport installation, i forgot to install
Blockquote
--uuids
If you have a similar error, follow the steps below to fix:
NOTE: You must have laravel passport installed already, if not, them follow the complete installtion guide Here
Step 1:
Install passport uuids
php artisan passport:install --uuids
Your result will look something like
After creating, the uuid for your application, you will have to include it in your .env file as such:
PASSPORT_PERSONAL_ACCESS_CLIENT_ID=986eb40c-0458-4b6e-bead-ea2fc4987033
PASSPORT_PERSONAL_ACCESS_CLIENT_SECRET=VXLdTpqWK9i3CBqFwZgje5fuerQ5Uf2lvwXJqBoP
And there you go, you can now try to do what you couldn't do before.

Creating auth tokens for a custom model that is not the default User model

How do I create access/api/auth tokens for a different model? From most questions, docs, or tutorials, most are using the default User model.
I read the default doc but it doesn't really say where to substitute the default Model class or how to verify against non-Model classes.
Any suggestions?
To use a different model than User for Laravel Sanctum API authentication.
This is for Laravel 8.
Create new model, php artisan make:model ModelName -m
the flag m is used to instantiate a migration file for this model.
Go to the Model class file and extend it with Illuminate\Foundation\Auth\User, ensure it uses HasApiTokens, and list out your fillable fields for record creation.
...
use Illuminate\Foundation\Auth\User as Authenticatable;
class ModelName extends Authenticatable{
use ..., HasApiTokens;
protected $fillable = [...]
}
Go to config/auth.php and add new provider and new guard.
'guards' => [
...
,
'api' => [
'driver' => 'sanctum',
'provider' => 'model-name',
'hash' => false,
]
],
'providers' => [
...
,
'model-name' => [
'driver' => 'eloquent',
'model' => App\Models\ModelName::class,
]
]
Go to your api routes and wrap your routes as below.
Route::middleware(['auth:sanctum'])->group(function(){
Route::get('/whatever-route-name',function(){
return 'Authenticated';
});
});
Download Postman or your favored API testing tool, send a GET request to [http://localhost:8000/api/whatever-route-name](http://localhost:8000/api/whatever-route-name) , in Headers, ensure Accept has a value of applcation/json, send the request, and it should return an {”message”: “Unauthenticated.”}
Go to your public routes, create a dummy route to create a record for ModelName
After creation ensure that you call $model_name→createToken($model_name→whatever_field)→plaintTextToken; to get the plain text api key.
Go to back to your API test tool, under Authorization, choose Bearer Token and supply the api key returned from above.
The route wrapped in auth:sanctum is now accessible.

Feathers - Authentication and Authorization

I have created an app using Feathers. I've been using this app for a while. It successfully hosts a blog and some other web pages. However, I've now reached a point where I need to protect some of my routes. For example, I want to have a route for my administrative activitivies (/admin), but I only want specific users to have access.
I know that I need to use the authentication and authorization components. However, at this time, I'm stuck on the authorization. My goal is to authenticate using OAuth via Google. However, to get past my authentication challenge, I'd be happy with just using a hard-coded username / password just to get the /admin route locked down (no, it's not deployed).
At the moment, I have
const app = feathers();
const routes = require('./routes');
app.configure(configuration(path.join(__dirname, '..')));
app.use(compress())
.options('*', cors())
.use(cors())
.use(favicon( path.join(app.get('public'), 'favicon.ico') ))
.use('/public', serveStatic(app.get('public'), staticFileSettings ))
.use(bodyParser.json())
.use(bodyParser.urlencoded({ extended: true }))
.configure(routes)
.configure(hooks())
.configure(rest())
.configure(socketio())
.configure(services)
.configure(middleware)
.configure(authentication())
;
// Setup the authentication strategy.
app.authenticate({
type: 'local',
'email': 'admin#feathersjs.com',
'password': 'admin'
}).then(function(result){
console.log('Authenticated!', result);
}).catch(function(error){
console.error('Error authenticating!', error);
});
My problem is, as soon as I add the block of code with the app.authenticate stuff, I get an error when I start my app. The error says:
TypeError: app.authenticate is not a function
If I remove app.authenticate(...); My app starts fine, but nothing is locked down. In my ./routes/index.js file, I have:
app.use('/admin', function(req, res) {
res.render('admin/index.html', {});
});
Which, renders just fine. It's just not restricted to an authenticated and authorized user. What am I missing? At a bare minimize I'm trying to understand how to get past the app.authenticate error.
In order to protect a route from unauthorized access you need to follow the documented usage of express middleware provided by the feathers-authentication package that is installed when you do feathers generate authentication.
Here's an example of authenticating the /admin route.
const auth = require('feathers-authentication');
app.use(
'/admin',
auth.express.authenticate('jwt'), // <-- this is a strategy, can local/jwt... etc
(req, res, next) => {
console.log("Request for '/admin'...");
res.render('admin');
}
);

Passport - "Unauthenticated." - Laravel 5.3

I hope someone could explain why I'm unauthenticated when already has performed a successfull Oauth 2 authentication process.
I've set up the Passport package like in Laravel's documentation and I successfully get authenticated, receives a token value and so on. But, when I try to do a get request on, let say, /api/user, I get a Unauthenticated error as a response. I use the token value as a header with key name Authorization, just as described in the docs.
Route::get('/user', function (Request $request) {
return $request->user();
})->middleware("auth:api");
This function is suppose to give back my self as the authenticated user, but I'm only getting Unauthenticated. Likewise, if I just return the first user, I'm again getting Unauthenticated.
Route::get('/test', function(Request $request) {
return App\User::whereId(1)->first();
})->middleware("auth:api");
In a tutorial from Laracast, guiding through the setup of Passport, the guider doesn't have the ->middleware("auth:api") in his routes. But if its not there, well then there's no need for authentication at all!
Please, any suggestions or answers are more then welcome!
You have to set an expiration date for the tokens you are generating,
set the boot method in your AuthServiceProvider to something like the code below and try generating a new token. Passports default expiration returns a negative number
public function boot()
{
$this->registerPolicies();
Passport::routes();
Passport::tokensExpireIn(Carbon::now()->addDays(15));
Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));
}
Check your user model and the database table, if you have modified the primary id field name to say something other than "id" or even "user_id" you MIGHT run into issues. I debugged an issue regarding modifying the primary id field in my user model and database table to say "acct_id" instead of keeping it as just "id" and the result was "Unauthenticated" When I tried to get the user object via GET /user through the auth:api middleware. Keep in mind I had tried every other fix under the sun until I decided to debug it myself.
ALSO Be sure to UPDATE your passport. As it has had some changes made to it in recent weeks.
I'll link my reference below, it's VERY detailed and well defined as to what I did and how I got to the solution.
Enjoy!
https://github.com/laravel/passport/issues/151
I had this error because of that I deleted passport mysql tables(php artisan migrate:fresh), php artisan passport:install helps me. Remember that after removing tables, you need to re-install passport!
I had exactly the same error because I forgot to put http before the project name.
use Illuminate\Http\Request;
Route::get('/', function () {
$query = http_build_query([
'client_id' => 3,
'redirect_uri' => 'http://consumer.dev/callback',
'response_type' => 'code',
'scope' => '',
]);
// The redirect URL should start with http://
return redirect('passport.dev/oauth/authorize?'.$query);
});
Route::get('/callback', function (Request $request) {
$http = new GuzzleHttp\Client;
$response = $http->post('http://passport.dev/oauth/token', [
'form_params' => [
'grant_type' => 'authorization_code',
'client_id' => 3,
'client_secret' => 'M8y4u77AFmHyYp4clJrYTWdkbua1ftPEUbciW8aq',
'redirect_uri' => 'http://consumer.dev/callback',
'code' => $request->code,
],
]);
return json_decode((string) $response->getBody(), true);
});

Google + sign in with laravel

I have been struggling a lot for G+ sign-in with laravel, I have downloaded the php-sdk using composer. I am also using JavaScript to sign-in, once the once the user signs in I redirect him to a route from JavaScript to /gLogin?email=abc#gmail.com&name=John Doe where I have following code.
$user_profile['email']=Input::get('email');
$user_profile['name']=Input::get('name');
$user_id=DB::table('users') -> where('dyp_user_email', $user_profile['email'])-> pluck('dyp_user_id');
if($user_id)
{
$user_to_be_logged_in=new user();
$user_to_be_logged_in = User::find($user_id);
}
else
{
$password=$token = str_random(16);
$hash=Hash::make($password);
$user_to_be_logged_in = user::create(array('dyp_user_type' => 'IN', 'dyp_name' => $user_profile['name'], 'dyp_user_email' => $user_profile['email'], 'dyp_mobile_number' => '','dyp_password'=> $hash,'dyp_user_status' => 'VF'));
$data = array('name' => $user_to_be_logged_in -> dyp_name, 'password' => $password);
Mail::send('emails.fbUserRegistration', $data, function($message) use ($user_to_be_logged_in) {
$message -> to($user_to_be_logged_in->dyp_user_email, $user_to_be_logged_in->dyp_name) -> subject('Thanks for registering with dreamyourproperty.com');
});
}
Auth::login($user_to_be_logged_in);
There is a serious security problem here, that I am not able to validate the user's session.
I someone manually hits the url /gLoin?email=abc#gmail.com&name=xyz then also my code will authenticate him.
In comparison to G+ signin FB login was pretty simple.Can someone provide me guidance, I am seriously stuck with this part.
They way you want to handle this is /gLogin?access_token=xyz where xyz is the users Google+ access_token. Make a request to people.get authenticated with that access token. That way you have server side validation the current user is validated for the specific Google+ profile.