Registration error in Laravel - laravel

I use the default auth/registration in Laravel 5.3.
When I try to register new user I get error:
FatalThrowableError in RegistersUsers.php line 33:
Call to undefined method Illuminate\Auth\TokenGuard::login()
I have made some changes in configuration Laravel:
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
So, by default I use api guard

The authentication driver api you are trying to use is TokenBased. That means the server will issue your client a Token on successful authentication using credentials. Then, client can present this token to server while making the request to identify itself.
As given in laravel git, there isn't any method as login().
To use the TokenBased Authentication, here's the good guide

Related

Laravel 7 UI - Sessions Guard Driver - Spatie Permission Package

In short: The Sessions guard driver is rejecting my login attempts.
Before creating the Laravel UI I had already created a authentication system for my frontend using JWT as the api guard driver.
I installed the Laravel UI in order to use the Spatie Permission Package which had also been installed and had generated some extra tables.
Once the Laravel UI was installed I successfully registered a new user but was not redirected to the home screen. I attempted to log in as the new user and got a response stating that my credentials were not recognised. I then tried to log in with a user that had been previously created in the users table through the frontend registration...
Whilst it gave no error this time it still did not redirect me. I then attempted to log into the frontend app with the newly created user and was able to do so. At this point I figured there was a conflict with the tokens.
I looked in RegisterController.php and saw the following:
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
My frontend JWT auth system also uses User.php and so I had a look and saw that the password was being encrypted twice. First with Hash:: and then with bcrypt. I therefore removed the Hash encryption.
I registered successfully but again was not redirected to home. I attempted to log in again and was again unable to do so, but this time I received no error message! The registered user was now behaving in the same manner as users registered through the front end app.
I went through the code line-by-line spending hours logging out values etc. and could see that everything was being accepted and I was being redirected to home but the HomeController.php was then passing my credentials through the auth guard which was rejecting then and then redirecting me back to login!!
The only way I can access home is by changing the middleware in HomeController.php from 'auth' to 'guest':
public function __construct()
{
$this->middleware('guest'); // changed from 'auth'
}
In the Spatie documention it states the following:
If your app uses only a single guard, but is not web (Laravel’s default, which shows “first” in the auth config file) then change the order of your listed guards in your config/auth.php to list your primary guard as the default and as the first in the list of defined guards. While you’re editing that file, best to remove any guards you don’t use, too.
I therefore switched the guards around in config/auth.php so that api was first but it had no effect.
'guards' => [
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
'web' => [
'driver' => 'session',
'provider' => 'users',
],
],
The frontend is using the api guard and the backend is using web but they are both using the same app/User. This I guess must be the cause of the problem but I am new to Laravel and, after hours of reading and testing, I am still struggling. What does it want that I am missing!? The password is now being accepted so it cannot be that..
Any help would be very much appreciated. Thank you.
The problem was in the top section of config/auth which I had missed:
'defaults' => [
'guard' =>'api',
'passwords' => 'users',
],
It wasn't that I was being rejected by the web session driver - it was that the web guard was being overwritten by the api guard in the defaults section above.
I have to specify in the routing which middleware I wanted so as to avoid the default:
Route::get('/home', [
'middleware' => 'auth:web', 'uses' => 'HomeController#index'])->name('home');
EDIT: Since auth:web was only used by a couple of controllers the better solution was to change the default guard in config/auth to web and then do Route::group with the rest that used the api guard:
Route::group([
'middleware' => 'api'
], function () {
Route::post('login', 'AuthController#login');
Route::post('register', 'AuthController#register');
Route::post('logout', 'AuthController#logout');
Route::post('refresh', 'AuthController#refresh');
});

Always response 401 (Unauthorized) for my Laravel Passport generated OAuth 2 token

I am using:
Postman/Insomnia for REST checking
Laravel 5.6 with Laravel Passport
Vagrant (Apache 2, PHP 7.2)
Made all checklist described on Laravel Docs for Laravel Passport and after certain steps I receive HTTP 401 for my valid OAuth access token.
Requested by /oauth/token/ the new access token with client_id and client_secret.
Used received access token to authorize my simple Laravel REST test controller with included Oauth api middleware.
The end is one: 401 unauthorized :(
So, here is some of my configurations:
Apache
api route
Kernel.php
PassportServiceProvider.php
AuthServiceProvider.php
I had a very similar issue too:
The difference between your codes and mine:
In the routes/api.php, i used only auth:api.
I didn't create PassportServiceProvider.php in the app folder.
In the Kernel.php mine is client not client_credentials.
I used client_credentials as grant_type in the POST request call.
In the result I always got 401.
Until I created a user using Password Grant Client:
php artisan passport:client --password
And changed client_credentials to password in the POST request call:
$http = new GuzzleHttp\Client;
$response = $http->post('http://your-app.com/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => 'client-id',
'client_secret' => 'client-secret',
'username' => 'taylor#laravel.com',
'password' => 'my-password',
'scope' => '',
],
]);
$access_token = json_decode((string) $response->getBody(), true)['access_token'];
Put the access token returned in the Bearer of the headers, and it works.
And also you can get the current user using $request->user();
If you are using client_credentials as grant_type, it's going through the client middleware, so in the middleware auth:api needs to be removed.
This is because Apache does not, by default, pass authorization headers to PHP. You need to edit your Apache site configuration to add a line to Deskpro's directive. Note that this configuration must be added directly to Apache's configuration (e.g., adding it to htaccess will not work
<VirtualHost>
# ...
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
# ...

Can I use OAuth and Auth at the same time in Laravel?

I am doing a project in which I have implemented private chat in Laravel. But for the third party, we use OAuth but i have already used auth() in my project. Can I use both? OAuth is getting token, then communicate with Vue.js. So, I don't want to remove auth() functions in my project. Can you please guide me what to do?
Real time chat system in laravel project. I'm using separate Vue.js with Laravel.
Yes. You can use both OAuth and default Laravel Auth at the same time. In default, Laravel provides routes as web.php and api.php.
web.php: This route uses default Laravel Auth functionality
api.php: Routes defined here uses OAuth functionality
Make sure you use default driver as web in config/auth.php
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],

Lumen: add middleware to package defined routes

I have a problem with adding middleware to existing routes of a vendor package. I building an API on top of Lumen (micro-services framework created by Laravel). I am using Passport for oauth authentication and imported this package: https://github.com/dusterio/lumen-passport to use Passport in Lumen. I have implemented a custom route for requesting a token and want to block requests to the existing passport route: /oauth/token. But I also need the route myself in order to redirect token requests from my custom route.
I have tried to override the existing route like this:
$app->post('/oauth/token', [
'middleware' => 'reject',
'uses' => '\Dusterio\LumenPassport\Http\Controllers\AccessTokenController#issueToken'
]);
But this throws a 500 back at me without Exception tracing.
I am using a custom route for requesting a token in order to set the set the token scope based on the role of a user. I am using the scope to check the role of a user (or app with other grant types), the normal token route of Passport should be blocked to everyone except Lumen self. With this only Lumen should be able to set the scope.
TLDR: How can I add middleware to package defined routes in Lumen.
The latest merge of https://github.com/dusterio/lumen-passport supports prefixing the passport routes.
I added "dusterio/lumen-passport": "dev-master", to my composer.json and Dusterio\LumenPassport\LumenPassport::routes($app, [ 'prefix' => 'api/v1/protected', 'middleware' => 'reject', ]); at the end of my bootstrap/app.php.
See this issue for additional information: https://github.com/dusterio/lumen-passport/issues/31

laravel oAuth2.0-server error

i am using https://github.com/lucadegasperi/oauth2-server-laravel in laravel framework for creating Api's. i configured all setup. when i make a call to get token it shows
{ "error": "invalid_request", "error_description": "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed. Check the "grant_type" parameter." }
My grant type is -
'grant_types' => [ 'client_credentials' => [ 'class' => '\League\OAuth2\Server\Grant\ClientCredentialsGrant', 'access_token_ttl' => 3600 ] ],
token is -
'token_type' => 'League\OAuth2\Server\TokenType\Bearer', i need sample url for access my api.. whether i need to pass access token where can i get access token.
i dont find any tut about geting access token and use them correctly. please help me on this..
thanks in advance.
I am using the same package with laravel 5. There is this tutorial that explains it well.
After you publish the package settings, run migrations and add some test data in the oauth_clients and your users tables. Specifically you add client_id and client_secret in the oauth_clients table. Also create a user with username and password in your users table. Finally using POSTMAN chrome extension provide the following data to a POST route to get your access_token.
grant_type as password,
client_id as what you added above,
client_secret as what you just created above,
username your test username,
password your test user password,
You should get correct access_token from POSTMAN.
I think what you need is to include your client_id and secret_id parameters
that you got from github when you created your OAuth application. I use socialite and I had used the following information inside config/services.php
'github' => [
'client_id' => 'CLIENT_ID',
'client_secret' => 'CLIENT_SECRET',
'redirect' => 'REDIRECT_RUL'
]
Of course that's a temporary solution, if you use laravel 5 I suggest you to save this information inside .env files as they are more secure.
More about .env more about socialite

Resources