I'm using Laravel 6. I want to generate a new API token for the user each time the user logged in.
Referring to some answers on StackOverflow, there is a method authenticated in LoginController which is been called just after the user is logged in successfully. I cannot find the authenticated method in Laravel 6.
Is there a new way to achieve the same thing in Laravel 6?
As per Laravel Documentation:
If you need more robust customization of the response returned when a
user is authenticated, Laravel provides an empty authenticated(Request
$request, $user) method that may be overwritten if desired:
/**
* The user has been authenticated.
*
* #param \Illuminate\Http\Request $request
* #param mixed $user
* #return mixed
*/
protected function authenticated(Request $request, $user)
{
return response([
//
]);
}
Just place the following method inside app\Http\Controllers\LoginController (overriding it):
use Illuminate\Http\Request;
protected function authenticated(Request $request, $user)
{
// stuff to do after user logs in
return redirect()->intended($this->redirectPath());
}
Reference:
Laravel -> Authentication -> Authenticating
Related
I am working on a Laravel 8 project. I have noticed that a couple of things have changed including authentication. I am using Jetstream for authentication.
I have installed the Jetstream and I can register and login going to the route /register and /login on the browser. What I am doing now is that for local development, I am creating seeder class so that I can seed the users and log in using those seeded users for local development. But when I log in using those account, it is always complaining that "These credentials do not match our records.".
This is what I have done. I have registered an account on browser using password, "Testing1234". The password hash is saved in the users table. I copied the password and use it in the UserFactory class as follow.
<?php
namespace Database\Factories;
use App\Models\Role;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
class UserFactory extends Factory
{
use WithFaker;
/**
* The name of the factory's corresponding model.
*
* #var string
*/
protected $model = User::class;
/**
* Define the model's default state.
*
* #return array
*/
public function definition()
{
return [
'name' => $this->faker->name,
'email' => $this->faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => '$2y$10$tive4vPDzIq02SVERWxkYOAeXeaToAv57KQeF1kXXU7nogh60fYO2', //Testing.1234
'remember_token' => Str::random(10),
];
}
}
Then I created a user using factory as follow.
User::factory()->create(['email' => 'testing#gmail.com']);
Then I tried to log in using the user I just created. But it is always complaining, "These credentials do not match our records.". I cannot use the other passwords too. Even the default password that comes with the default user factory class. What is wrong with my code and how can I fix it?
Try using
User::factory()->make([
'email' => 'testing#gmail.com',
]);
I have finally found the issue.
In the JetstreamServiceProvider class, I have added the following code to customise the login flow.
Fortify::authenticateUsing(function (Request $request) {
});
My bad. That is what makes it failing.
I am trying to login and logout from a create-react-app application which uses an application with Laravel 7.x as backend. Where can I put the custom response message for /login and /logout auth routes in Laravel 7.x. I used the artisan command for auth scaffolding.
I know about Single Page Application authentication in Laravel. It is given in the Laravel Sanctum page. https://laravel.com/docs/7.x/sanctum. I have followed everything there and have no problems with that.
I get redirected to /home route even when I have commented out the line in LoginController.php
protected $redirectTo = RouteServiceProvider::HOME;
I tried to look up the documentation https://laravel.com/docs/7.x/authentication it says "Laravel provides an empty authenticated(Request $request, $user) method that may be overwritten if desired:". But don't know where this method can be written.
So I will answer my own question. This method is present in the trait AuthenticatesUsers.php which is present in vendor/laravel/ui/auth-backend/ directory.
I added this in the empty method called authenticated() in AuthenticateUsers.php trait present in above link.
/**
* The user has been authenticated.
*
* #param \Illuminate\Http\Request $request
* #param mixed $user
* #return mixed
*/
protected function authenticated(Request $request, $user)
{
return new Response(['success' => 'you have been authenticated'], 200);
}
For custom logout response, use the loggedOut() method in AuthenticatesUsers.php trait.
Hope this helps someone. I also created a pull request in the docs repository, hope it gets accepted. Thanks.
I need to force all routes with SSL in Lumen 5.6.
For examples http://www.mywebsite.com to https://www.mywebsite.com
I tried many different solutions on the web, but nothing worked for me:
Middelware, .htaccess, AppServiceProvider
Which the best way to force SSL scheme in Lumen 5.6?
You can create a middleware class and use the redirect()->to function with the secure parameter set to true.
To achieve this, create a class (HttpsProtocol.php) and place it in the middleware directory:
namespace App\Http\Middleware;
use Closure;
class HttpsProtocol{
/**
* #param \Illuminate\Http\Request $request
* #param Closure $next
*
* #return \Illuminate\Http\Response|\Laravel\Lumen\Http\ResponseFactory|mixed
*/
public function handle($request, Closure $next) {
if (!$request->secure() && app()->environment() === 'production') {
return redirect()->to($request->getRequestUri(), 302, [], true);
}
return $next($request);
}
}
And add the middleware to your $app->middleware array found in app.php.
$app->middleware([
App\Http\Middleware\HttpsProtocol::class
]);
I just upgraded my application from Laravel 5.4 to v 5.5. Non authenticated users are not redirecting properly now.
Normally a non authenticated user should be redirected to /manage/login but it is redirected to /login route.
Everything was working perfect in Laravel v 5.4
My app contain two guards.
Routing in web.php
Auth::routes();
Route::middleware(['auth:manager'])->group(function () {
Route::get('/manage', 'Manage\AdminController#dashboard')->name('manage.home');
});
So before upgrade a non authenticated user trying to access /manage was redirected to /manage/login but after upgrading it is redirecting to /login.
I have Auth Controllers copied and modified as needed in Manage\Auth.
Similarly Views are in folder structure Manage\Auth.
My LoginController in Controllers\Manage\Auth
|
Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/manage/';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function showLoginForm()
{
return view('manage.auth.login');
}
public function logout(Request $request)
{
$this->guard()->logout();
$request->session()->flush();
$request->session()->regenerate();
return redirect('/manage');
}
protected function guard()
{
return Auth::guard('manager');
}
I faced the same problem, and it's quit simple to solve.
the point is that if you are using guards you were probably handling unauthenticated exception in your app/Exceptions/Handler.php . when using laravel 5.4 .
After update to 5.5 this is done under vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php .
You should refer to this Laravel 5.5 change unauthenticated login redirect url for more details about how to solve it.
I have followed this excellent tutorial Building a Web App with Lumen and OAuth2 for setting up OAuth2 and Lumen. Everything is working fine apart from now I want to access the currently authenticated user information/model.
My route correctly posts the supplied information after I have logged in and I can break with Netbeans inside the controller but I am not clear how to get the user from the underlying Auth framework. I have tried the three methods indicated here Authentication - Laravel but to no avail. The lumen logs shows:
==== routes.php ====
$app->group(['namespace' => 'App\Http\Controllers','prefix' => 'api', 'middleware' => 'oauth'], function($app)
{
$app->post('info', 'InfoController#send');
}
==== InfoController.php ====
namespace App\Http\Controllers;
// the controllers
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Contracts\Auth\Authenticatable;
class InfoController extends Controller{
/* /api/info methods */
public function send(Request $request){
// can iterate over the entire users table but I just
// want the current user (must be some method through
// the authentication stack)
$users = \App\Auth\User::all();
foreach ($users as $user) {
$name = $user->name;
$key = $user->getAuthIdentifier();
$pwd = $user->getAuthPassword();
}
// CODE GETS HERE BUT how to get the current user?
// Authenticated OK (request supplies "Access-Token: Bearer ...")
}
}
This is probably not the cleanest solution and may not match your requirements exactly but it does retrieve the user.
I decided to make another DB query in the proxy to get the user with the same key (in my case, email address) that was requested by the client.
In my case I was sending the user id along with the standard oauth token.
You could use the same technique to set some value in the session.
// ../app/Auth/Proxy.php
namespace App\Auth;
use App\User; // ----- added this line
use GuzzleHttp\Client;
class Proxy {
...
private function proxy($grantType, array $data = [])
{
...
$response = json_decode($guzzleResponse->getBody());
if (property_exists($response, "access_token")) {
...
// added the following line to get the user
$user = User::where('email',$data['username'])->get()->first();
// untested, but you could add the user to your session here
$request = app()->make('request');
$request->session()->put('current_user', $user);
$response = [
'accessToken' => $response->access_token,
'accessTokenExpiration' => $response->expires_in,
'userId' => $user->id,
];
}
...