Me encuentro con un problema que quizá sea muy básico y no lo estoy visualizando. En síntesis, tengo un proyecto de laravel 8 funcionando correctamente con apis usando JWT para la parte de tokens.
Resulta que tengo la necesidad de iniciar sesión también desde el login web de laravel (auth login)
A través de mis apis, incluyendo el del auth/login
todo funciona correctamente, sin embargo al querer iniciar sesión desde el login web no funciona y me redirige a la misma vista del login una vez ingresado el username y el password correctamente.
Por otro lado, entre mis ajustes para hacer funcionar JWT y mis apis, modifiqué mi LoginController
y mi AuthController
de forma en que mis apis pudieran iniciar sesión con el campo de username
de mi base de datos en lugar del clásico campo email
Para solucionar mi problema y buscando en internet, probé cambiando algunas rutas en el api.php
, sin embargo sigue sin funcionar el login en la web y ya no sé qué más pudiera cambiar de forma en que me funcionen mis apis usando JWT y el login web.
Agradeceré cualquier aporte que pudiera ayudarme a solucionar mi problema.
Mis archivos serían estos:
api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use \App\Http\Controllers\RegistrosController;
use App\Http\Controllers\AuthController;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::group([
'middleware' => 'api',
'prefix' => 'auth'
], function ($router) {
Route::post('/login', [AuthController::class, 'login']);
Route::post('/register', [AuthController::class, 'register']);
Route::post('/logout', [AuthController::class, 'logout']);
Route::post('/refresh', [AuthController::class, 'refresh']);
Route::get('/user-profile', [AuthController::class, 'userProfile']);
});
Route::group(['middleware' => ['jwt.auth', 'can:agregar_observaciones', 'can:ver_todos_registros']], function () {
Route::get("/registros/ver-registros-admin/{registro_id?}", [RegistrosController::class, "verRegistrosAdmin"])->name("registros.ver_registros_admin");
Route::post("/registros/agregar-observaciones", [RegistrosController::class, "agregarObservaciones"])->name("registros.agregar_observaciones");
});
Route::group(['middleware' => ['jwt.auth', 'can:guardar_nuevos_registros', 'can:ver_registros_usuario']], function () {
Route::get("/registros/ver-registros-usuario/{registro_id?}", [RegistrosController::class, "verRegistrosUsuario"]);
Route::post("/registros/guardar-registro", [RegistrosController::class, "guardarRegistro"]);
Route::post("/registros/agregar-foto", [RegistrosController::class, "saveImage"]);
});
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| 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 = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function username()
{
return 'username';
}
}
AuthController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Validator;
class AuthController extends Controller
{
/**
* Create a new AuthController instance.
*
* @return void
*/
public function __construct() {
$this->middleware('auth:api', ['except' => ['login', 'register']]);
}
/**
* Get a JWT via given credentials.
*
* @return \Illuminate\Http\JsonResponse
*/
public function login(Request $request){
$validator = Validator::make($request->all(), [
'username' => 'required|string',
'password' => 'required|string|min:6',
]);
$response = [
"data" => [],
"message" => "Credenciales incorrectas",
"success" => false,
];
if ($validator->fails()) {
return $response;
}
if (! $token = auth()->attempt($validator->validated())) {
return $response;
}
$auth = $this->createNewToken($token);
return $response = [
"data" => $auth,
"message" => "",
"success" => true,
];;
}
/**
* Register a User.
*
* @return \Illuminate\Http\JsonResponse
*/
public function register(Request $request) {
$validator = Validator::make($request->all(), [
'name' => 'required|string|between:2,100',
'email' => 'required|string|email|max:100|unique:users',
'password' => 'required|string|confirmed|min:6',
]);
if($validator->fails()){
return response()->json($validator->errors()->toJson(), 400);
}
$user = User::create(array_merge(
$validator->validated(),
['password' => bcrypt($request->password)]
));
return response()->json([
'message' => 'User successfully registered',
'user' => $user
], 201);
}
/**
* Log the user out (Invalidate the token).
*
* @return \Illuminate\Http\JsonResponse
*/
public function logout() {
auth()->logout();
return response()->json(['message' => 'User successfully signed out']);
}
/**
* Refresh a token.
*
* @return \Illuminate\Http\JsonResponse
*/
public function refresh() {
return $this->createNewToken(auth()->refresh());
}
/**
* Get the authenticated User.
*
* @return \Illuminate\Http\JsonResponse
*/
public function userProfile() {
return response()->json(auth()->user());
}
/**
* Get the token array structure.
*
* @param string $token
*
* @return \Illuminate\Http\JsonResponse
*/
protected function createNewToken($token){
$user = auth()->user();
$user['role'] = $user->roles->pluck('name')->first();
unset($user['roles']);
return [
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60,
'user' => $user
];
/*return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60,
'user' => $user
]);*/
}
}
User.php
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
use HasFactory, Notifiable, HasRoles;
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* @return array
*/
public function getJWTCustomClaims()
{
return [];
}
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
'username',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
config/auth.php
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
Y para finalizar así están compuestas mis rutas:
+--------+----------+----------------------------------------------------+---------------------------------+------------------------------------------------------------------------+--------------------------------------------+
| Domain | Method | URI | Name | Action | Middleware |
+--------+----------+----------------------------------------------------+---------------------------------+------------------------------------------------------------------------+--------------------------------------------+
| | GET|HEAD | / | | Closure | web |
| | POST | api/auth/login | | App\Http\Controllers\AuthController@login | api |
| | POST | api/auth/logout | | App\Http\Controllers\AuthController@logout | api |
| | | | | | auth:api |
| | POST | api/auth/refresh | | App\Http\Controllers\AuthController@refresh | api |
| | | | | | auth:api |
| | POST | api/auth/register | | App\Http\Controllers\AuthController@register | api |
| | GET|HEAD | api/auth/user-profile | | App\Http\Controllers\AuthController@userProfile | api |
| | | | | | auth:api |
| | POST | api/registros/agregar-foto | | App\Http\Controllers\RegistrosController@saveImage | api |
| | | | | | Tymon\JWTAuth\Http\Middleware\Authenticate |
| | | | | | can:guardar_nuevos_registros |
| | | | | | can:ver_registros_usuario |
| | POST | api/registros/agregar-observaciones | registros.agregar_observaciones | App\Http\Controllers\RegistrosController@agregarObservaciones | api |
| | | | | | Tymon\JWTAuth\Http\Middleware\Authenticate |
| | | | | | can:agregar_observaciones |
| | | | | | can:ver_todos_registros |
| | POST | api/registros/guardar-registro | | App\Http\Controllers\RegistrosController@guardarRegistro | api |
| | | | | | Tymon\JWTAuth\Http\Middleware\Authenticate |
| | | | | | can:guardar_nuevos_registros |
| | | | | | can:ver_registros_usuario |
| | GET|HEAD | api/registros/ver-registros-admin/{registro_id?} | registros.ver_registros_admin | App\Http\Controllers\RegistrosController@verRegistrosAdmin | api |
| | | | | | Tymon\JWTAuth\Http\Middleware\Authenticate |
| | | | | | can:agregar_observaciones |
| | | | | | can:ver_todos_registros |
| | GET|HEAD | api/registros/ver-registros-usuario/{registro_id?} | | App\Http\Controllers\RegistrosController@verRegistrosUsuario | api |
| | | | | | Tymon\JWTAuth\Http\Middleware\Authenticate |
| | | | | | can:guardar_nuevos_registros |
| | | | | | can:ver_registros_usuario |
| | GET|HEAD | api/user | | Closure | api |
| | | | | | auth:api |
| | GET|HEAD | home | home | App\Http\Controllers\HomeController@index | web |
| | | | | | auth |
| | GET|HEAD | login | login | App\Http\Controllers\Auth\LoginController@showLoginForm | web |
| | | | | | guest |
| | POST | login | | App\Http\Controllers\Auth\LoginController@login | web |
| | | | | | guest |
| | POST | logout | logout | App\Http\Controllers\Auth\LoginController@logout | web |
| | GET|HEAD | password/confirm | password.confirm | App\Http\Controllers\Auth\ConfirmPasswordController@showConfirmForm | web |
| | | | | | auth |
| | POST | password/confirm | | App\Http\Controllers\Auth\ConfirmPasswordController@confirm | web |
| | | | | | auth |
| | POST | password/email | password.email | App\Http\Controllers\Auth\ForgotPasswordController@sendResetLinkEmail | web |
| | GET|HEAD | password/reset | password.request | App\Http\Controllers\Auth\ForgotPasswordController@showLinkRequestForm | web |
| | POST | password/reset | password.update | App\Http\Controllers\Auth\ResetPasswordController@reset | web |
| | GET|HEAD | password/reset/{token} | password.reset | App\Http\Controllers\Auth\ResetPasswordController@showResetForm | web |
| | GET|HEAD | register | register | App\Http\Controllers\Auth\RegisterController@showRegistrationForm | web |
| | | | | | guest |
| | POST | register | | App\Http\Controllers\Auth\RegisterController@register | web |
| | | | | | guest |
+--------+----------+----------------------------------------------------+---------------------------------+------------------------------------------------------------------------+--------------------------------------------+