laravel passport giving Unauthenticated error - laravel

I am using laravel passport but when I try to hit the post route that gives me user data it's giving me error like
{"message":"Unauthenticated."}
here is my controller method
public function getDetails()
{
$user = Auth::user();
return response()->json(['success' => $user], $this->successStatus);
}
api.php
Route::post('register', 'API\PassportController#register')-
>name('register');
Route::post('login', 'API\PassportController#login')->name('login');
//Route::post('details', 'API\PassportController#getDetails')->middleware('auth:api');
Route::group(['middleware' => 'auth:api'], function(){
Route::get('user', 'API\PassportController#user');
Route::post('details', 'API\PassportController#getDetails');
});
screenshot of postmen
please let me know what inputs you want from my side

Your codes look ok to me, but if I'm not mistaken you added your "Authorization" manually: please try this way from the image below, by clicking on Authorization tab, left next to Headers tab.
And make sure that your token is the one that is returned from the server when you make login request: see the image below.

Related

Laravel Fortify returns Not Found

I send a xhr request to /login route. It does login, but the response is an html with text Not Found. I realize that fortify is saying this coz it cant find the logged in view. I have enabled views, 'views' => true in config/Fortify.php. But I want Fortify to return a success response text after successful login. How can I do this?
You can customise your response based on the request type:
public function func(Request $request)
{
if ($request->ajax()) {
return response()->json('AJAX response', 200);
}
return view('my-view');
}

how to validate jwt token in Laravel thorugh postman

I am a beginner in Laravel. I have successfully generated a jwt token, and I want to send this token to another api which will authenticate it and sends the response of dishes. But my code is not validating the token, and gives me the response even if I send the wrong token.
How can I solve this?
Code:
class DishController extends Controller
{
public function self()
{
try{
$user = Auth->user();
$dishes = Dish::all();
}
catch(\Tymon\JWTAuth\Exceptions\UserNotDefinedException $e){
return response()->json(['error' => $e->getMessage()]);
}
return response()->json($dishes);
}
}
Api route
Route::get('/dish/self',[
'as' =>'login.login',
'uses' => 'DishController#self'
]);
in your route, you should gives a middleware (apiJwt), see below the code:
Route::middleware("apiJwt")->get('/dish/self',[
'as' =>'login.login',
'uses' => 'DishController#self'
])
something like this
remember, you should install some packages like the tymon/jwt-auth

Login by code seems to not work in laravel

Basically i'm trying to send by email a link that lets you login with a specific account and then redirects you to a page.
I can seccessfully generate link and send them via email using URL functionalities in laravel using this code:
Generating the link:
$url = "some/page/".$travel_id;
$link = URL::temporarySignedRoute(
'autologin', now()->addDay(), [
'user_id' => 3,
'url_redirect' => $url,
]
);
And sending the mail:
Mail::send('emails.travel', $data, function ($message) use ($data) {
$message->from('mail#mail.com', 'blablabla');
$message->to('reciever#mail.com', 'blablabla')->subject('test');
});
There is a route that catches the link sent by mail that is supposed to log you in with the user (in this case, the one with the id '3') and redirect you to some page but when it redirects, it prompts you to the login page, as if you are not logged.
Here is the route:
Route::get('/autologin', function (Request $request) {
$user = User::findOrFail($request->user_id);
if (! $request->hasValidSignature()) {
abort(403);
}
Auth::login($user);
return redirect($request->input('url_redirect'));
})->name('autologin');
When i try to do a Auth::check() after the Auth::login($user); it returns true, so is the user logged in?
I also tried to use Auth::loginUsingId($request->user_id); with no different results.
Any idea of what's happening?
So i found the problem,
I was logging in with a backpack user but i was using the default auth feature of laravel.
Turns out i need to use: backpack_auth()->login($user); instead of Auth::login($user); if i want to login using a backpack user.
Also use backpack_auth()->check() instead of Auth::check().

Unable to logout via an ajax request in Laravel

I am using Laravel 5.1 and I am trying to setup a simple login/logout system. I can easily login using:
Auth::attempt(['email' => $request->email, 'password' => $request->password]);
But if I try to logout via an ajax request using Auth::logout();, it does not log out the user. Manually going to the logout route in a browser tab however works just fine.
note: if my controller looks like this:
public function logout()
{
Auth::logout();
dd(Auth::user());
}
Then the request returns null. This should indicate the user has been logged out, but if I pass another request - I am still logged in.
Edit
Ajax call:
import request from 'superagent'
request.get(env.api + endpoint)
.withCredentials()
.set({
'X-Requested-With': 'XMLHttpRequest'
})
.end((err, res) => {
if (err) return reject(err);
return resolve(res.body);
})
EDIT
I found the source of my problem. It was a single route that looked like this:
Route::get('image/users/{image}', ['as' => 'fetch.users.images', 'uses' => 'Files#fetchUserImage']);
Changing the route path image/users/{image} solved my problem. Still curious as to why this caused an error with Auth? The route was not interfering with any of my other routes.
Edit
My above edit was wrong. It is to do with that route but its not the naming.
I am requesting an image from the route Route::get('image/users/{image}', ['as' => 'fetch.users.images', 'uses' => 'Files#fetchUserImage']); whose associated controller looks like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Storage;
class Files extends Controller
{
public function __construct()
{
$this->middleware('basic');
}
public function fetchUserImage($image)
{
$image = 'users/images/' . $image;
if (Storage::disk('s3')->exists($image)) {
return response(Storage::disk('s3')->get($image), 200, ['Content-Type' => 'image/jpeg']);
} else {
return response('Image not found', 404);
}
}
}
I am requesting the image with JS like this:
let img = new Image();
img.onload = () => this.state.update ? this.setState({image: props.src}) : null;
img.src = this.props.src;
When Laravel returns 404 or false or anything that isn't an image, the JS sends the request again. After I logout, Laravel still has an image request to process and the response('Image not found', 404) gets triggered after my logout succeeds and then as the response contains the logged in session info, my browser gets indirectly logged back in.
Haven't come up with a fix for this yet. Not sure how to go about it.

Redirects an authenticated user back to the originally requested URL or the default URL in laravel

I am new at laravel and I want to achieve the following results, let's say a guest gets to the result page after searching for a term and then decides to login, how can I get the user to login and keep the same result page in laravel
I have the following code
in the filters.php I have the following:
Route::filter('guest', function()
{
if (Auth::check()) return Redirect::to('/');
});
then in the user controller I have the following
the show login function
public function login()
{
return View::make('users.login');
}
the handle login function
public function handleLogin()
{
$data = Input::only(['email', 'password']);
if(Auth::attempt(['email' => $data['email'], 'password' => $data['password']])){
return Redirect::to('/profile');
}
return Redirect::route('login')->withInput();
}
right now the default page after login goes to the profile page but I want the user to go back to wherever he was before login.
any help? thanks
I think that's what you looking for
return Redirect::back();
In Laravel 4, you can use Redirect::guest and Redirect::intended to achieve your target easily.
Redirect::guest put the current URL into the session before redirect to the target URL.
Redirect::intended check whether there is any URL saved in the session, redirect to that URL or a default location if it does not exist.
In action, your code can be:
if(Auth::attempt(['email' => $data['email'], 'password' => $data['password']])){
return Redirect::guest('/profile');
}
and after log in
if (Auth::check()) return Redirect::intended();

Resources