I try make rest API with Laravel 8 + Sanctum. And my database is MySql Maria DB.
I create LoginController and make function call login. When i try my API, it's always return Unauthorized. I pretty sure my USERNAME and PASSWORD is correct.
This is my LoginController
public function store(Request $request) {
$user = User::create(
[
"USERNAME" => $request->username,
"PASSWORD" => Hash::make($request->password),
"ADM_MST_SITE_ID" => 0,
]
);
$token = $user->createToken('apiToken')->plainTextToken;
$res = [
'user' => $user,
'token' => $token
];
return response($res, 201);
}
public function login(Request $request)
{
$data = $request->validate([
'username' => 'required|string',
'password' => 'required|string'
]);
$user = User::where('username', $data['username'])->first();
$credentials = request(['username', 'password']);
if(!Auth::attempt($credentials))
return response()->json([
'message' => 'Unauthorized'
], 401);
$token = $user->createToken('apiToken')->plainTextToken;
$res = [
'user' => $user,
'token' => $token
];
return response($res, 201);
}
Model
////
protected $table = 'adm_mst_user';
protected $guarded = ['ID'];
public function getAuthPassword()
{
return $this->PASSWORD;
}
////
The store function is work well, the new data are inserted to my database. But, when i login with username and password, it's not working.
I try 2 different auth check, using Auth::attempt and Hash::check.
I don't know where the error coming from. It's always return Unauthorized.
$user = User::where('username', $data['username'])->first();
$this->guard()->login($user);
and make a guard function in same controller
protected function guard()
{
return Auth::guard();
}
import use Illuminate\Support\Facades\Auth; in top
include
use Illuminate\Support\Facades\Hash;
You need to make it with email not with username
$credentials = request(['email', 'password']);
OR, modify your attempt code
if(!Auth::attempt(['username' => $credentials['username'], 'password' => $credentials['password']))
this code worked with sanctum
use App\Models\User;
use Illuminate\Support\Facades\Hash;
function login($candidate)
{
$user = User::where('username', $candidate['username'])->first();
if (!$user || !Hash::check($candidate['password'], $user->password)) {
return [
'message' => 'These credentials do not match our records.'
];
}
$token = $user->createToken('my-token')->plainTextToken;
return [
'user' => $user,
'token' => $token
];
}
Related
I am working on a project (web and api) and using Laravel sanctum in my project, I am trying to make an api get request on postman to see user information after logged in but I keep getting this "message": "Unauthenticated." error but I notice that when I was using the get to access user information from my api on localhost (http://127.0.0.1:8000/) it was showing the details and working fine, but when I test it with my domain url (http://sotun.com/mark/live) show Unauthenticated.
My Controller
class AuthApiController extends Controller
{
public function login(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.'],
]);
}
$token = $user->createToken($request->device_name)->plainTextToken;
$response = [
'user' => $user,
'token' => $token,
];
return response ($response, 201);
}
public function user(Request $request)
{
return $request->user();
}
}
api.php
use App\Http\Controllers\AuthApiController;
Route::group(['middleware' => ['auth:sanctum']], function() {
Route::get('/user', [AuthApiController::class, 'user']);
Route::post('/logout', [AuthApiController::class, 'logout']);
});
User Model
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable implements MustVerifyEmail
{
use HasApiTokens, HasFactory, Notifiable;
protected $fillable = [
'name',
'email',
'password',
'user_id',
'user_type',
'user_job',
];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
In the .env I added the below
.env
SANCTUM_STATEFUL_DOMAIN=http://sotun.com/mark/live
SESSION_DOMAIN=http://sotun.com/mark/live
postman output
But the same result, please I will help to solve this Thanks
Modify your .env file configurations to:
SANCTUM_STATEFUL_DOMAINS="sotun.com,127.0.0.1:8000"
SESSION_DOMAIN=sotun.com
Notice the pluralization of the environmental variable SANCTUM_STATEFUL_DOMAINS.
I was recently updating from laravel's sanctum to passport; and there is this one test that bothers me a lot.
In sanctum there is this method under the PersonalAccessToken model that finds the token and returns the token if it exists.
I don't seem to find anything like that in the docs or online.
I'm validating the test by asserting that $user->tokens is not empty... yet I wish to validate that the token I'm returning from my login controller is indeed a token; not just the creation;
Thnx in advance...
Login Test
public function user_can_login()
{
//$this->withoutExceptionHandling();
$user = User::factory()->create();
$url = route('api.v1.auth.login', [
'email' => $user->email,
'password' => 'password'
]);
$res = $this->jsonApi()
->post($url)
->assertStatus(200);
$token = $res->json(['access_token']);
$this->assertNotEmpty($user->tokens);
}
Login method in authcontroller
public function login(Request $request)
{
$request->validate([
'email' => 'required|email',
'password' => 'required',
]);
$credentials = $request->only(['email', 'password']);
if (Auth::attempt($credentials)) {
$user = Auth::user();
$access_token = $user->createToken('laravel-api.local')->accessToken;
return response()->json(['access_token' => $access_token], 200);
} else {
return response()->json(['error' => 'Unauthorized'], 401);
}
}
pues:dont know why im writing the code, but just for ref of what i'm doing
https://laracasts.com/discuss/channels/testing/how-do-i-create-a-route-while-testing
solution is quite simple... you'll find it here... I had an issue when I tried that before hand and it seems to be with the use of the Route::name('name') method and the route('name') function threw a server error. but if you call the path directly it should work...
any who... authController and login method stay the same but the test changes to...
public function setUp(): void
{
parent::setUp();
Route::middleware('auth:api')
->get('/test-route', function (Request $request) {
return $request->user();
});
$clientRepository = new ClientRepository();
$client = $clientRepository->createPersonalAccessClient(
null,
'Personal Access Client Test',
'/'
);
DB::table('oauth_personal_access_clients')->insert([
'client_id' => $client->id,
'created_at' => date('Y-m-d'),
'updated_at' => date('Y-m-d'),
]);
}
/** #test */
public function user_can_login_with_correct_credentials()
{
//$this->withoutExceptionHandling();
$user = User::factory()->create();
$url = route('api.v1.auth.login', [
'email' => $user->email,
'password' => 'password',
'device_name' => $user->name . ' test Device'
]);
$res = $this->jsonApi()
->post($url)
->assertStatus(200);
$token = $res->json(['access_token']);
$this->jsonApi()
->withHeader('Authorization', 'Bearer ' . $token)
->get('/test-route')
->assertStatus(200);
}
I am trying to register a new user into my system, and right after make the login automatically. How can I call another function in the same Controller and pass $request variables to it?
I did the var_dump, login function is getting data, the login is being made, but it's not redirecting to index (line 28)
public function login(Request $request)
{
//var_dump($request->only('email', 'password'));
$credentials = [
'email' => $request->email,
'password' => $request->password,
];
if(Auth::attempt($credentials)) {
return redirect()->route('movie.index');
}
return redirect()->route('login')->with([
'error' => 'danger',
'msg' => 'Error message',
]);
}
public function register(Request $request)
{
$newUser = new User;
$newUser->name = $request->name;
$newUser->email = $request->email;
$newUser->password = Hash::make($request->password);
$newUser->save();
$this->login($request);
}
Right way is
Auth::login($newUser);
Then redirect to your page after login.
I use passport in my laravel project to authenticate users by api. API work correctly on my local host. But after i deploy it on Plesk server token doesnt create. Always show Server Error.
public function login(Request $request) {
$validator = Validator::make($request->all(),[
'email' => 'required',
'password' => 'required',
]);
if($validator->fails()) {
return response()->json(["validation errors" => $validator->errors()]);
}
$email = $request->email;
$password = $request->password;
error_log($password);
$user = DB::table("users")->where([["email", "=", $email]])->first();
if(is_null($user)) {
return response()->json(["success" => false, "message" => "User doesn't exist"]);
}
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
$user = Auth::user();
$token = $user->createToken('token')->accessToken;
$success['success'] = true;
$success['user'] = $user;
$success['message'] = "Success! you are logged in successfully";
$success['token'] = $token;
return response()->json(['success' => $success ], 200);
} else {
return response()->json(['error' => 'Unauthorised'], 401);
}
}
$token = $user->createToken('token')->accessToken;
This line throw error
Problem was in my AuthServiceProvider
class AuthServiceProvider extends ServiceProvider
{
protected $policies = [
'Medicare\Model' => 'Medicare\Policies\ModelPolicy',
];
public function boot()
{
$this->registerPolicies();
Passport::routes();
//
}
}
After i commented 'Medicare\Model' => 'Medicare\Policies\ModelPolicy' everything works fine.
I just wanted to say if the user is not active, don't allow to login. I have made the controller as below, I am not sure what I am missing or what else I have to do here to make this work!
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Auth\Authenticatable;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
public function authenticate()
{
if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
// Authentication passed...
return redirect()->intended('dashboard');
}
}
}
My thinking was authenticate() method should do the trick!
The below code worked for my case:
protected function getCredentials(Request $request)
{
return [
'email' => $request->input('email'),
'password' => $request->input('password'),
'active' => true
];
}
for Laravel 5.3 need to add following code to LoginController
protected function credentials(Request $request)
{
return [
'email' => $request->input('email'),
'password' => $request->input('password'),
'active' => true
];
}
i think you should create method to check if user passed your credentials, here's my suggestion :
protected function getCredentials(Request $request)
{
return [
'username' => $request->input('email'),
'password' => $request->input('password'),
'active' => true
];
}
and your login method:
public function login(Request $request) {
$this->validate($request,['email' => 'required|email','password' => 'required']);
if (Auth::guard()->attempt($this->getCredentials($request))){
//authentication passed
}
return redirect()->back();
}
hope you get basic idea.
In LoginController.php file write this function
protected function credentials(Request $request) {
$extraFields = [
'user_type'=> 'customer',
'user_entry_status' => 1
];
return array_merge($request->only($this->username(), 'password'), $extraFields);
}
Go to this path :
your-project-folder/vendor/laravel/framework/src/illuminate/Foundation/Auth/AuthenticatesUsers.php
$credentials=$request->only($this->loginUsername(), 'password');
$credentials['status'] = '1';
return $credentials;
Change getCredantials works fine, but it is good practice to let user know, that the account was suspended (credentials are OK, but the account status is not). You can easily override login method in Auth/LoginController.php to your own copy, add your own logic to login process and raise own exception.
in Auth/LoginController.php create login and sendAccountBlocked function
/*load additional classes to LoginController.php*/
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Auth;
public function login(Request $request){
//
$this->validateLogin($request);
//
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if (method_exists($this, 'hasTooManyLoginAttempts') && $this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if ($this->attemptLogin($request)) {
//check user status
if (Auth::user()->user_status == 'A') return $this->sendLoginResponse($request);
// if user_status != 'A' raise exception
else {
$this->guard()->logout();
return $this->sendAccountBlocked($request);
}
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
//
}//
protected function sendAccountBlocked(Request $request){
throw ValidationException::withMessages([
$this->username() => ['Your account was suspended.'],
]);
}