Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

guildsmac's avatar

Auth::attempt returning false (API)

I'm creating an API for a table called usuarios, everything went all right when i registered a new user through postman, but when I try to login, the Auth::attempt, passing a username(not an email) and a password, it returns false, returning code 401, Unauthorized. I think it is because i changed deleted the default users table and created a new one. Can anybody help me? Maybe if I changed the table and columns for Authentication it would work, but I don't know how to do it. Code for my AuthController:

class AuthController extends Controller
{
    public function signup(Request $request)
    {
        $request->validate([
            'nome' => 'required|string',
            'email' => 'required|string|email|unique:usuarios',
            'cpf' => 'required|string|unique:usuarios',
            'username' => 'required|string|unique:usuarios',
            'dtNasc' => 'string',
            'senha' => 'required|string|confirmed'
        ]);

        $user = new Usuario([
            'nome' => $request->nome,
            'email' => $request->email,
            'cpf' => $request->cpf,
            'username' => $request->username,
            'dtnasc' => $request->dtnasc,
            'senha' => Hash::make($request->senha)
        ]);

        $user->save();

        return response()->json([
            'message' => 'Successfully created user!'
        ], 201);
    }

    public function login(Request $request)
    {
        $request->validate([
            'username' => 'required|string',
            'senha' => 'required|string',
            'remember_me' => 'boolean'
        ]);


        $credentials = request(['username', 'senha']);

        if(!Auth::attempt($credentials))
            return response()->json([
                'message' => 'Unauthorized'
            ], 401);

        $user = $request->user();

        $tokenResult = $user->createToken('Personal Access Token');
        $token = $tokenResult->token;

        if ($request->remember_me)
            $token->expires_at = Carbon::now()->addWeeks(1);

        $token->save();

        return response()->json([
            'access_token' => $tokenResult->accessToken,
            'token_type' => 'Bearer',
            'expires_at' => Carbon::parse(
                $tokenResult->token->expires_at
            )->toDateTimeString()
        ]);
    }

    public function logout(Request $request)
    {
        $request->user()->token()->revoke();

        return response()->json([
            'message' => 'Successfully logged out'
        ]);
    }

    public function user(Request $request)
    {
        return response()->json($request->user());
    }
}
0 likes
8 replies
s4muel's avatar

you need two things:

  • customize the username in LoginController.php:
public function username()
{
    return 'username';
}
  • customize the password field in the App\User.php
public function getAuthPassword()
{
    return $this->senha;
}

and make sure your App\User model extends Illuminate\Foundation\Auth\User (a.k.a. Authenticatable), but i think you already do.

1 like
guildsmac's avatar

Thank you for answering me, I did what you said but i'm still getting this from postman { "message": "Unauthorized" }

I created this AuthController.php for managing my API, so do I still have to make changes in LoginController.php?

michalurva's avatar

Check your routes.

You need GUEST access to your AuthController@signup and AuthController@login

guildsmac's avatar
Route::group([
    'prefix' => 'auth'
], function () {
    Route::post('login', 'AuthController@login');
    Route::post('signup', 'AuthController@signup');

    Route::group([
        'middleware' => 'auth:api'
    ], function() {
        Route::get('logout', 'AuthController@logout');
        Route::get('user', 'AuthController@user');
    });
});

That's my api.php from routes folder

I don't think it is because of Guest access because i'm successfully registering Users with Postman

michalurva's avatar

Yeah, routes looks good. Whats the name of your new users table?

Do you have correctly set config/auth.php ?

guildsmac's avatar

It's usuarios

I changed some 'users' to 'usuarios'

<?php

return [
    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],
    
    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'passport',
            'provider' => 'usuarios',
        ],
    ],
    
'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Usuario::class,
        ],
    ],

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],

];


I'm also trying to use the column username as the authentication method, not the email column.

michalurva's avatar

This

'api' => [
    'driver' => 'passport',
    'provider' => 'usuarios'
],

should be

'api' => [
    'driver' => 'passport',
    'provider' => 'users'
],

Please or to participate in this conversation.