cakephp 3.0 Auth & single sign on - authentication

I am using cakephp 3.0 and in the login page although I try to enter the right credentials i get invalid username or password message.
In my user table , I have the fields username and password by which i want to authenticate user.
I have tried to follow the cake book documentation for 3.0 except the step where for including password hashing.Also used the table structure similiar to the one in cakephp documentation
Is it because it is accessing the wrong table?I have mentioned the fields in App Controller
Also if i have to implement single sign on ,is there a plugin which could help me out?Please provide links to such tutorials as this is important for my graduate studies project
My model file:
class UsersTable extends Table
{
public function initialize(array $config)
{
$this->table('users');
$this->displayField('User_id');
$this->primaryKey('User_id');
$this->addBehavior('Timestamp');
}
public function validationDefault(Validator $validator)
{
$validator
->add('id', 'valid', ['rule' => 'numeric'])
->notEmpty('id', 'create')
->notEmpty('username','Username is required')
->notEmpty('password','Password is required')
->notEmpty('role');
return $validator;
}
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->isUnique(['username']));
return $rules;
}
}
My UserController file
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Core\App;
use Cake\Event\Event;
class UsersController extends AppController
{
public function view($id = null)
{
$user = $this->Users->get($id, [
'contain' => []
]);
$this->set('user', $user);
$this->set('_serialize', ['user']);
}
public function register()
{
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success('The user basic details has been saved.');
} else {
$this->Flash->error('The user could not be saved. Please, try again.');
}
}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
}
public function edit($id = null)
{
$user = $this->Users->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success('The user has been saved.');
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error('The user could not be saved. Please, try again.');
}
}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
}
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$user = $this->Users->get($id);
if ($this->Users->delete($user)) {
$this->Flash->success('The user has been deleted.');
} else {
$this->Flash->error('The user could not be deleted. Please, try again.');
}
return $this->redirect(['action' => 'index']);
}
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
// Allow users to register and logout.
// You should not add the "login" action to allow list. Doing so would
// cause problems with normal functioning of AuthComponent.
$this->Auth->allow(['register', 'logout']);
}
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
$this->set('user',$user);
if ($user) {
$this->Auth->setUser($user);
$this->Flash->error(__('Login successful'));
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error(__('Invalid username or password, try again'));
}
}
public function logout()
{
return $this->redirect($this->Auth->logout());
}
public function index()
{
$this->set('users', $this->paginate($this->Users));
$this->set('_serialize', ['users']);
}
}
My AppController file
class AppController extends Controller
{
public function initialize()
{
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'username',
'password' => 'password'
]
]
],
'loginRedirect' => [
'controller' => 'Orders',
'action' => 'view'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'display',
'home'
]
]);
$this->Auth->allow(['display']);
}
public function beforeFilter(Event $event)
{
$this->Auth->allow(['index', 'view', 'display','login']);
}
}
My login page:
<div class="users_form">
<?=$ this->Flash->render('auth') ?>
<?=$ this->Form->create() ?>
<fieldset>
<legend>
<?=_ _( 'Please enter your username and password') ?>
</legend>
<?=$ this->Form->input('username') ?>
<?=$ this->Form->input('password') ?>
</fieldset>
<?=$ this->Form->button(__('Login')); ?>
<?=$ this->Form->button(__('Register')); ?>
<?=$ this->Form->end() ?>
</div>

I figured out what was wrong.
First place I had not included the password hasher method.
On trying to include that ,I added it to the wrong module.It must be added for the Entity class file whereas I was adding it to The UserTable.php.
This was not helping my case at all.I followed the manual to the T .
After adding the password Hasher module I added a new user.
Also it is true that it works only if the password length is varchar(255)
Therefore the user along with hashed password was created.
I was then able to login

Related

How to generate token with JWT on Laravel 9

The problem is that it does not generate the TOKEN, throwing the following error
TypeError: Lcobucci\JWT\Token\Builder::relatedTo(): Argument #1 ($subject) must be of type string, null given
When I make the request through the post verb, it performs all the previous validation but when it comes to generating the token, the error occurs.
`
public function login(Request $request)
{
$credentials = $request->only('usuario', 'password');
$validator = Validator::make($request->all(), [
'usuario' => 'required',
'password' => 'required'
]);
if ($validator->fails()) {
return response()->json([
'message' => $validator->errors(),
'token' => null
], 404);
}
$user = usuarios::where('usuario', $request->usuario)->first();
if (!$user) {
return response()->json([
'message' => 'Usuario no registrado.',
'token' => null
], 401);
}
$isValid = Hash::check($request->password, $user->password);
if (!$isValid) {
return response()->json([
'message' => 'ContraseƱa incorrecta.'
]);
}
$token = JWTAuth::fromUser($user);
return response()->json([
'message' => 'Usuario logueado correctamente',
'token' => $token
]);
}
`
And my code mode is this
`
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
//AƱadimos la clase JWTSubject
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Notifications\Notifiable;
class usuarios extends Model implements JWTSubject
{
use HasFactory, HasApiTokens, Notifiable;
protected $table = 'usuarios';
protected $fillable = [
'tipo_usuario',
'acceso_pv',
'nombre',
'usuario',
'password',
];
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
public $timestamps = false;
}
`

Yii2 - Bad Request (#400) Missing required parameters in index.php

I have problem for action view, update, and delete in index.php page, it always show bad request (#400) Missing required parameters: id_kategori and the address always go to localhost/training/frontend/web/index.php?r=kategori%2F(view/update/delete)&id=1, but when i change the address manually to localhost/training/frontend/web/index.php?r=kategori%2Fview&id_kategori=1 it's no problem, also i can create action but then it will redirect page to localhost/training/frontend/web/index.php?r=kategori%2Fview&id=1. Here's the code, its generate from Gii CRUD:
public function actionView($id_kategori)
{
return $this->render('view', [
'model' => $this->findModel($id_kategori),
]);
}
public function actionUpdate($id_kategori)
{
$model = $this->findModel($id_kategori);
if ($this->request->isPost && $model->load($this->request->post()) && $model->save()) {
return $this->redirect(['view', 'id_kategori' => $model->id_kategori]);
}
return $this->render('update', [
'model' => $model,
]);
}
public function actionDelete($id_kategori)
{
$this->findModel($id_kategori)->delete();
return $this->redirect(['index']);
}
Should i rename id_kategori column to id and other id_column just to id?
Version: Yii 2 (2.0.43)
Template: Advanced Template
define $id_kategori=null in function
public function actionView($id_kategori=null)
{
return $this->render('view', [
'model' => $id_kategori ? $this->findModel($id_kategori) : null,
]);
}
You need to do like this
public function actionView($id) {
return $this->render('view', [
'model' => $this->findModel($id),
]);
}

Lumen JWT Auth always return 401 in other route after login success

I have lumen + jwt restapi with custom users table (ex : pengguna) with nomor as primary key and tgl_lahir as password..there is no problem with api/login and it's generate a token but when i try with other route such as api/buku, the return always 401 unauthorized although the authorization header contains valid token after login
my models like
<?php
namespace App;
use Illuminate\Auth\Authenticatable;
use Laravel\Lumen\Auth\Authorizable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Model implements AuthenticatableContract, AuthorizableContract, JWTSubject
{
use Authenticatable, Authorizable;
protected $primaryKey = 'nomor';
protected $table = 'pengguna';
public $timestamps = false;
protected $fillable = [
'nomor','nama','alamat'
];
protected $hidden = [
'tgl_lahir ',
];
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
}
my BukuController
<?php
namespace App\Http\Controllers;
use App\Buku;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class BukuController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function showAllBuku()
{
return response()->json(Buku::all());
}
}
my routes
$router->group(['prefix' => 'api'], function () use ($router) {
$router->post('login', 'AuthController#login');
$router->get('buku', ['uses' => 'BukuController#showAllBuku']);
});
config/auth.php
<?php
return [
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => \App\User::class
]
],
];
the existing pengguna table don't allowed created ID field like lumen/laravel auth, if i commented code in Middleware\Authenticate like :
public function handle($request, Closure $next, $guard = null)
{
//if this block commented is working
if ($this->auth->guard($guard)->guest()) {
return response('Unauthorized.', 401);
}
return $next($request);
}
it's working..is there another way for my case?thanks for your help
sorry my mistake, my problem solved by add this in user model
public function getAuthIdentifierName(){
return $this->nomor;
}
public function getAuthIdentifier(){
return $this->{$this->getAuthIdentifierName()};
}

Yii2 Login failed to validate password

As the title says, i have a little bit of trouble in this area of the application. So basically, in my UserController i hash the password & in the login page it's verified with the standard security tool. Everything from the form to the user is good, but the check fails to return true. I don't have any interactions with the password in beforeSave/beforeValidate. Any ideas?
UserController:
public function actionRegister()
{
$model = new User(['scenario' => 'register']);
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->password_usr = Yii::$app->security->generatePasswordHash($model->password_usr);
if ($model->save()) {
Yii::$app->session->setFlash('success', 'User created');
return $this->redirect('/site/login');
} else {
die(print_r($model->getErrors()));
}
}
return $this->render('register', [
'model' => $model,
]);
}
SiteController:
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->login();
return $this->goBack();
}
$model->password = '';
return $this->render('login', [
'model' => $model,
]);
}
User model:
public function validatePassword($password)
{
return Yii::$app->security->validatePassword($password, $this->password_usr);
}
Login form is the default as the yii2 generates
Maybe this is a problem
die(print_r($model->getErrors()));
login
public function actionLogin()
{
$this->layout = "login";
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
$model->password = '';
}
return $this->render('login', [
'model' => $model,
]);
}
signup
public function actionSignup()
{
$this->layout = "login";
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
the problem was the password field in the database, it was varchar(30) whilst generatePasswordHash returns a 60 char string

Cakephp 3 authentication

I'm working with Cakephp3 and I got problem with Auth system.
Here's my code in UsersController:
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error('Invalid username or password, try again');
}
}
In AppController:
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth',[
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'username',
'password' => 'password'
]
]
]]);
}
in login.ctp:
<?php
echo $this->Form->create();
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->button('log in');
echo $this->Form->end();
?>
and I've created a table called users which has fields: Full texts
id
first_name
last_name
username
password
created
modified
and I have sample user with the Username= hosein , password:123 but when I put in the data that does not work and says invalid username of password.
really why?!