auth laravel always return false - php

I often create a login with Laravel, and it runs smoothly, but I don't understand the actual process run by Laravel php artisan make:auth. and now I want to try creating this login process myself to understand the actual process
I'm trying to make the login process run by myself without Laravel make:auth. create a user table with a password that hashed. when logging in Auth::attempt is always false, why?
public function authenticate(Request $request)
{
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
// Authentication passed...
return redirect()->intended('dashboard');
}
}
This function is in the documentation of Laravel Manually Authenticating Users
if i dd(Auth::attempt($credentials)); always return false, so it can't go to route /home:
and my register controller like this:
public function create()
{
$user = User::create([
'name' => Input::get('name'),
'email' => Input::get('email'),
'password' => Hash::make(Input::get('password')),
]);
return redirect::back();
}
how to deal with this?

i think laravel use json callback and middlware and some handled session and cookie
better use basic auth
and check by step to all work currectly in front to end
and see data send to backend currectly

Related

Laravel : How can I modify auth:sanctum middleware to return a 401 instead of redirect to login route?

Good evening,
I encounter a problem using Laravel and Sanctum to build an Api for a Mobile application.
I followed the documentation and define a route to get a token :
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;
});
Tested it with postman, everything works fine, if I pass the right login and password, I'm able to get my token.
Now the problem I'm facing : I protected a route as the documentation said by using this middleware :
Route::middleware('auth:sanctum')->get(' ....'
If I pass my token in headers, it works, but if I don't, Laravel tries to redirect me to /login route, which I don't want of course because I'm creating a mobile application.
** What I want is to receive a 401 if my token isn't valid. **
I tried to define a new middleware and copy the verification of the 'auth:sanctum' but I can't even find where this is defined, since it is not in the Kernel.php file.
I hope someone could explain me how I could find the code of 'auth:sanctum', so I can understand it and create a middleware with the comportement I need, but any help would be appreciate.
Thanks you in advance.

Lumen 5.8 Auth attempt does not exist

I'm new to Lumen and building a RESTful API and I got stuck for how many hours now because Auth::attempt is not working. I've been searching for any answers but all the results are only Laravel not Lumen.
So I created a AuthController and login method to authenticate user but I got an error.
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|string|email',
'password' => 'required|string',
]);
$credentials = $request->only('email', 'password');
if( !Auth::attempt($credentials) ) {
return response()->json([
'message' => 'Unauthorized'
], 401);
}
}
This is the error: "Method Illuminate\Auth\RequestGuard::attempt does not exist."
Anyone can help me? Thank you!
Can you try following:
if (!Auth::guard('web')->attempt($credentials) {
return response()->json([
'message' => 'Unauthorized'
], 401);
}
The method is only available for routes which are using the web middleware, could you check that out?
You may need to edit your config/auth file.
Lumen Passport Setup:
composer require dusterio/lumen-passport
Enable the app and auth service providers in bootstrap/app.php
add the following service providers in the bootstrap file
$app->register(Laravel\Passport\PassportServiceProvider::class);
$app->register(Dusterio\LumenPassport\PassportServiceProvider::class);
replace the contents inside the boot function of the auth service provider in /app/Providers/AuthServiceProvider with:
LumenPassport::routes($this->app->router);
Run php artisan migrate
run php artisan passport:install
Then follow this https://laravel.com/docs/5.8/passport#issuing-access-tokens
remeber the lumen version does not have views or routes for authorising access you have to build them seperatly on your client.

Un-signing/Decoding JWTs from internal API

I'm modifying our laravel site to authenticate users through our own internal API rather than just against passwords in the database.
When the API is called, and the user is verified as existing, it returns multiple JWTs with their own scopes. I need to un-sign, decode and cache those.
My issue is that I've looked into packages for laravel to do this with JWTs and even installed the Tymon library to look into it, but that seems to be more about issuing the tokens through Laravel.
I have this login function that, once the user signs in, dumps the encoded tokens on the login page view:
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required',
'password' => 'required',
]);
$credentials = $request->only('email', 'password');
$email = $request->input('email');
$password = $request->input('password');
$authService = new AuthService();
$login = $authService->loginGetToken($email, $password);
dd($login);
//var_dump($login); //this dumps upon 'sign in' then redirectes to login page
return redirect(route('auth.login'))
->with('login', $login);
}
So I've successfully returned my multiple JWTs from the API, but what is the best way to go about un-signing and decoding them here? I have a public key to use for the keys but I'm not sure how I can successfully dump unsigned and/or decoded tokens into the view so that I can see the scopes on my page for debugging.

Write web services with existing Laravel Controllers

I have a project in Laravel 5.2 and now I have to make the APIs for that. I tried to hit the localhost/myproject/login via postman as a post request with the parameters but it returns me the HTML in return. I have used Laravel's auth scaffolding for the authorization.
I am unable to find postLogin function in my project.
I have separated the routes but how can I change the existing functions for the API?
Route::group(array('prefix' => 'api/v1'), function()
{
Route::post('login', 'AuthController#postLogin');
});
Here is the postLogin that returns the json rather than the html code.
public function authenticate()
{
if (Auth::attempt(['email' => $email, 'password' => $password])) {
// Authentication passed...
//return redirect()->intended('dashboard');
return response()->json(['status' => 1]);
}
}
If you have any trouble, let me know.

PHP Laravel pass parameters as post data in redirect

After the registration was successful I wanted to pass all the data to a login route as POST. How do you do this in laravel 4?
I know I can just authenticate the user after registration but the login page has other parameters and more required authentication process.
So I wish to push the username and password entered in the registration process into the login process so it can go through with the other processes inside the login route. (ex. Token generation which requires post data of app_id and app_secret)
You can use Laravel Events do to that:
Register your event in filters.php or create an events.php and add it to composer.json:
Event::listen('user.registered', function($data)
{
var_dump($data['app_id']);
var_dump($data['app_secret']);
var_dump($data['user']);
});
And fire it in your register() method:
public function register()
{
/// register your user:
$user = new User;
...
$user->save();
/// fire the event:
Event::fire('user.registered', array(
'app_id' => 'API',
'app_secret' => 'WHATEVER',
'user' => $user
));
/// Redirect the user to where it should go next:
return Redirect::to('/');
}
Why not move alot of that extra logic into the User model. Then you can call $user->crazySecureLogin(); after logging in and after registering. That way you stay DRY, and it could possibly clean up your login controller method too. And to top it off, you don't have to worry about sending a post request as a response.
return Redirect::to('routename')->withInput();
or
return Redirect::to('routename')->with('email', $emailvalue)->with('password', $passwordValue)
etc
add namespace on top of your class
use Redirect;
add this code to your redirect stage.
return Redirect::route('route_name',['username' => $request->username,
'password' => $request->password]);

Categories