skip to Main Content

I have this controller:

class AuthController extends Controller
{
    public function login(Request $request)
        {
        if (!Auth::attempt($request->only('email', 'password'))) {
        return response()->json([
        'message' => 'Invalid login details'
                ], 401);
            }

        $user = User::where('email', $request['email'])->firstOrFail();

        $token = $user->createToken('auth_token')->plainTextToken;

        return response()->json([
                'access_token' => $token,
                'token_type' => 'Bearer',
        ]);
        }

    public function register(Request $request)
        {
        $validatedData = $request->validate([
                    'name' => 'required|string|max:255',
                    'email' => 'required|string|email|max:255|unique:users',
                    'username' => 'required|string|email|max:255|unique:users',
                    'password' => 'required|string|min:8',
        ]);

            $user = User::create([
                    'name' => $validatedData['name'],
                    'email' => $validatedData['email'],
                    'username' => $validatedData['username'],
                    'password' => Hash::make($validatedData['password']),
            ]);

        $token = $user->createToken('auth_token')->plainTextToken;

        return response()->json([
                    'access_token' => $token,
                    'token_type' => 'Bearer',
        ]);
        }

    public function me(Request $request)
    {
    return $request->user();
    }
}

And here is my api.php file for the routes:

Route::post('/me', [AuthController::class, 'me'])->middleware('auth:sanctum');
Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);

So if I do this post request with POstman: http://127.0.0.1/api/register?name=luis ruiz flores&[email protected]&username=llrr00&password=password
I should get a json with the access_token and the token_type, but what I get is the login view of my webpage.
Any idea why this happens?
Thak you.

3

Answers


  1. You should define Headers in postman to be {"Accept": "application/json"}
    to let laravel know this request will be JSON,enter image description here not a web response.

    Login or Signup to reply.
  2. Try setting Content-type header to application/json. I believe Laravel doesn’t allow a wildcard Content-type like */* when it returns json. But I might be very wrong about it. I just had the same issue and thats how I managed to resolve it.

    Also the url shouldn’t be the way it is. You send your authentication info in url query params, but sensitive info, like passwords, should be sent with POST http method, and should be inside the request body. Notice the ‘body’ tab instead of ‘Params’ tab.

    Setting Content-type in Postman

    Post request in Postman

    Login or Signup to reply.
  3. Controller

    use IlluminateHttpRequest;
    use IlluminateSupportFacadesAuth;
    use IlluminateSupportFacadesHash;
    use AppModelsUser;
    
    class AuthController extends Controller
    {
        public function login(Request $request)
        {
            $credentials = $request->only('email', 'password');
    
            if (!Auth::attempt($credentials)) {
                return response()->json([
                    'message' => 'Invalid login details'
                ], 401);
            }
    
            $user = $request->user();
            $token = $user->createToken('auth_token')->plainTextToken;
    
            return response()->json([
                'access_token' => $token,
                'token_type' => 'Bearer',
            ]);
        }
    
        public function register(Request $request)
        {
            $validatedData = $request->validate([
                'name' => 'required|string|max:255',
                'email' => 'required|string|email|max:255|unique:users',
                'username' => 'required|string|max:255|unique:users',
                'password' => 'required|string|min:8',
            ]);
    
            $user = User::create([
                'name' => $validatedData['name'],
                'email' => $validatedData['email'],
                'username' => $validatedData['username'],
                'password' => Hash::make($validatedData['password']),
            ]);
    
            $token = $user->createToken('auth_token')->plainTextToken;
    
            return response()->json([
                'access_token' => $token,
                'token_type' => 'Bearer',
            ]);
        }
    
        public function me(Request $request)
        {
            $user = $request->user();
    
            return response()->json($user);
        }
    }
    

    routes

    use AppHttpControllersAuthController;
    use IlluminateSupportFacadesRoute;
    
    Route::group(['prefix' => 'api'], function () {
        Route::post('/me', [AuthController::class, 'me'])->middleware('auth:sanctum');
        Route::post('/register', [AuthController::class, 'register']);
        Route::post('/login', [AuthController::class, 'login']);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search