Laravel 5.3 Auth Session Not Working - authentication

I did the Laravel update from 5.2 to 5.3 and when I put it on the server came the surprise, the sessions were not working ...
I already tried to do some things, but all to no avail ....
Web routes file
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('auth/facebook', 'SocialAuthController#redirect');
Route::get('auth/facebook/callback', 'SocialAuthController#handleProviderCallback');
Authentication file
/**
* Obtain the user information from Facebook.
*
* #return Response
*/
public function handleProviderCallback()
{
$user = Socialite::driver('facebook')->user();
$authUser = $this->findOrCreateUser($user);
$id = $authUser['id'];
$email = $authUser['email'];
$password = $authUser['senha'];
$credentials = array('email' => $email, 'password' => $password, 'excluded' => 0);
Auth::attempt($credentials);
Auth::loginUsingId($id);
If i run dd( Auth::user() ); the auth is working, but after the redirect the session is lose
Kernel file
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
}

To fix this i change the file session.php
Look for
'cookie' => 'laravel_session'
And change to
'cookie' => 'app_session',
After it every works fine

The answer below is not working.
When I upgraded to version 5.3 I needed to move the routes file and found that I needed to remove the web middleware line and this problem started ...
I just readjusted the line and it's working now.
Route::group(['middleware' => ['web']], function () {
Route::get('auth/facebook', 'SocialAuthController#redirect');
Route::get('auth/facebook/callback', 'SocialAuthController#handleProviderCallback');

Related

CakePHP 4 JWT integration: Token 'Signature verification failed'

I have tried to implement JWT based authentication in my CakePHP 4 application. Token is successfully generated and I have verified it on jwt.io as well. But while doing request for the route which should validate token it's giving following error "Authentication is required to continue".
While investigation the issue I the dd($this->Authentication); in the Controller's initialize function I see following reason In the object. "Signature verification failed" response.
Any help in this case?
Thanks,
Following is my code
routes.php
web related routes....
here are API related routes.
$routes->prefix('api', ['path' => '/api'], function ($routes) {
$routes->setExtensions(['json']);
// $routes->resources('register');
$routes->post('/user/add', ['controller' => 'User', 'action' => 'add']);
$routes->post('/user/login', ['controller' => 'User', 'action' => 'login']);
$routes->post('/user/index', ['controller' => 'User', 'action' => 'index']);
$routes->get('/user/logout', ['controller' => 'User', 'action' => 'logout']);
$routes->fallbacks(DashedRoute::class);
});
src/Application.php code
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* #copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* #link https://cakephp.org CakePHP(tm) Project
* #since 3.3.0
* #license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace App;
use Cake\Core\Configure;
use Cake\Core\ContainerInterface;
use Cake\Core\Exception\MissingPluginException;
use Cake\Datasource\FactoryLocator;
use Cake\Error\Middleware\ErrorHandlerMiddleware;
use Cake\Http\BaseApplication;
use Cake\Http\Middleware\BodyParserMiddleware;
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Http\MiddlewareQueue;
use Cake\ORM\Locator\TableLocator;
use Cake\Routing\Middleware\AssetMiddleware;
use Cake\Routing\Middleware\RoutingMiddleware;
use Authentication\AuthenticationService;
use Authentication\AuthenticationServiceInterface;
use Authentication\AuthenticationServiceProviderInterface;
use Authentication\Identifier\IdentifierInterface;
use Authentication\Middleware\AuthenticationMiddleware;
// use Cake\Http\MiddlewareQueue;
use Cake\Routing\Router;
use Psr\Http\Message\ServerRequestInterface;
/**
* Application setup class.
*
* This defines the bootstrapping logic and middleware layers you
* want to use in your application.
*/
class Application extends BaseApplication implements AuthenticationServiceProviderInterface
{
/**
* Load all the application configuration and bootstrap logic.
*
* #return void
*/
public function bootstrap(): void
{
$this->addPlugin('Migrations');
// Call parent to load bootstrap from files.
parent::bootstrap();
if (PHP_SAPI === 'cli') {
$this->bootstrapCli();
} else {
FactoryLocator::add(
'Table',
(new TableLocator())->allowFallbackClass(false)
);
}
/*
* Only try to load DebugKit in development mode
* Debug Kit should not be installed on a production system
*/
if (\Cake\Core\Configure::read('debug')) {
$this->addPlugin('DebugKit');
}
$this->addPlugin('Authentication');
// Load more plugins here
}
/**
* Setup the middleware queue your application will use.
*
* #param \Cake\Http\MiddlewareQueue $middlewareQueue The middleware queue to setup.
* #return \Cake\Http\MiddlewareQueue The updated middleware queue.
*/
public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
{
$csrf = new CsrfProtectionMiddleware(['httponly' => true]);
// Token check will be skipped when callback returns `true`.
$csrf->skipCheckCallback(function ($request) {
// Skip token check for API URLs.
// return $request->getPath() == '/dwolla_webhook';
return $request->getPath() == '/dwolla_webhook' || $request->getParam('prefix') == 'Api';
});
$middlewareQueue
// Catch any exceptions in the lower layers,
// and make an error page/response
->add(new ErrorHandlerMiddleware(\Cake\Core\Configure::read('Error')))
// Handle plugin/theme assets like CakePHP normally does.
->add(new AssetMiddleware([
'cacheTime' => \Cake\Core\Configure::read('Asset.cacheTime'),
]))
// ->add(function (
// \Psr\Http\Message\ServerRequestInterface $request,
// \Psr\Http\Server\RequestHandlerInterface $handler
// ) {
// try {
// // continue with the next middleware
// return $handler->handle($request);
// } catch (\Cake\Http\Exception\InvalidCsrfTokenException $exception) {
// // handle the catched exception
// $response = new \Cake\Http\Response();
// return $response->withStringBody('Oh noes, CSRF error!');
// }
// })
// Add routing middleware.
// If you have a large number of routes connected, turning on routes
// caching in production could improve performance. For that when
// creating the middleware instance specify the cache config name by
// using it's second constructor argument:
// `new RoutingMiddleware($this, '_cake_routes_')`
->add(new RoutingMiddleware($this))
// Parse various types of encoded request bodies so that they are
// available as array through $request->getData()
// https://book.cakephp.org/4/en/controllers/middleware.html#body-parser-middleware
->add(new BodyParserMiddleware())
// Cross Site Request Forgery (CSRF) Protection Middleware
// https://book.cakephp.org/4/en/controllers/middleware.html#cross-site-request-forgery-csrf-middleware
// ->add(new CsrfProtectionMiddleware([
// 'httponly' => true,
// ]));
->add($csrf)
->add(new AuthenticationMiddleware($this));
return $middlewareQueue;
}
/**
* Returns a service provider instance.
*
* #param \Psr\Http\Message\ServerRequestInterface $request Request
* #return \Authentication\AuthenticationServiceInterface
*/
public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
{
$service = new AuthenticationService();
// Load identifiers
$service->loadIdentifier('Authentication.Password', [
'fields' => [
'username' => 'username',
'password' => 'password',
],
// 'algorithm' => 'HS256',
'resolver' => [
'className' => 'Authentication.Orm',
// 'finder' => 'active',
'userModel' => 'User',
],
]);
// Load the authenticators
$service->loadAuthenticator('Authentication.Form', [
'fields' => [
'username' => 'username',
'password' => 'password',
],
'returnPayload' => false,
// 'loginUrl' => '/users/token.json'
]);
$service->loadAuthenticator('Authentication.Jwt', [
'secretKey' => file_get_contents(CONFIG . '/jwt.pem'),
'header' => 'Authorization',
// 'queryParam' => 'token',
'tokenPrefix' => 'Bearer',
'algorithm' => 'HS256',
'returnPayload' => false,
]);
$service->loadIdentifier('Authentication.JwtSubject', [
// 'tokenField' => 'id',
// 'dataField' => 'id',
'algorithm' => 'HS256',
]);
// Configure the service. (see below for more details)
return $service;
}
/**
* Register application container services.
*
* #param \Cake\Core\ContainerInterface $container The Container to update.
* #return void
* #link https://book.cakephp.org/4/en/development/dependency-injection.html#dependency-injection
*/
public function services(ContainerInterface $container): void
{
}
/**
* Bootstrapping for CLI application.
*
* That is when running commands.
*
* #return void
*/
protected function bootstrapCli(): void
{
try {
$this->addPlugin('Bake');
} catch (MissingPluginException $e) {
// Do not halt if the plugin is missing
}
$this->addPlugin('Migrations');
// Load more plugins here
}
}
APIController code
<?php
namespace App\Controller;
use Cake\Controller\Controller;
use Cake\Event\EventInterface;
class ApiController extends Controller
{
public function initialize(): void
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Authentication.Authentication');
}
private function setCorsHeaders()
{
$this->response = $this->response->cors($this->request)
->allowOrigin(['*'])
->allowMethods(['*'])
->allowHeaders(['x-xsrf-token', 'Origin', 'Content-Type', 'X-Auth-Token', 'Access-Control-Allow-Headers', 'Authorization', 'HTTP_Authorization', 'X-Requested-With'])
->allowCredentials(['true'])
->exposeHeaders(['Link'])
->maxAge(300)
->build();
}
public function beforeRender(EventInterface $event)
{
// .......
$this->setCorsHeaders();
}
public function beforeFilter(EventInterface $event)
{
// ......
if ($this->request->is('OPTIONS')) {
$this->setCorsHeaders();
return $this->response;
}
}
}
UserController code
<?php
namespace App\Controller\Api;
use Cake\View\JsonView;
use Firebase\JWT\JWT;
use App\Controller\ApiController;
use Lib\PpState\PpState;
class UserController extends ApiController
{
// public function viewClasses(): array
// {
// return [JsonView::class];
// }
public function initialize(): void
{
parent::initialize();
$this->loadModel('User');
// var_dump(debug_backtrace());
// dd($_SERVER['HTTP_AUTHORIZATION']);
dd($this->Authentication);
$this->Authentication->allowUnauthenticated(['login', 'add']);
// dd('hhesssssheh');
}
public function index()
{
// dd('ashsh');
$this->Authentication->logout();
// dd($this->Authentication->getResult());
// dd($this->Authentication);
$json = [
'success' => true,
'message' => 'welcome',
];
$this->set(compact('json'));
$this->viewBuilder()->setOption('serialize', 'json');
}
public function logout()
{
// JWT::destroy();
// $decoded = JWT::decode($jwt, new Key($key, 'HS256'));
// dd($decoded);
// dd($this->request);
//
// $result = $this->Authentication->getResult();
// dd($result);
// $json = ['route' => 'logout'];
// if ($result->isValid()) {
// $this->Authentication->logout();
// // $this->set('user', [
// // 'message' => 'You are successfully logout'
// // ]);
// $json = ['message' => 'You are successfully logout'];
// }
$json = [
'success' => true,
'message' => 'You are successfully logout',
];
$this->set(compact('json'));
$this->viewBuilder()->setOption('serialize', 'json');
// $this->viewBuilder->setOption('serialize', 'user');
// $this->set(compact('json'));
// $this->viewBuilder()->setOption('serialize', 'json');
// If the user is logged in send them away.
// if ($result->isValid()) {
// $target = $this->Authentication->getLoginRedirect() ?? '/home';
// return $this->redirect($target);
// }
// if ($this->request->is('post')) {
// $this->Flash->error('Invalid username or password');
// }
}
public function add()
{
if ($this->User->emailInUse($this->request->getData('username'))) {
$json = [
'success' => false,
'message' => 'User email already exists, Please choose different email',
];
} else {
$user = $this->User->newEntity($this->request->getData());
$newUser = $this->User->save($user);
if (!empty($newUser->id)) {
$privateKey = file_get_contents(CONFIG . '/jwt.key');
$payload = [
'iss' => 'myapp',
'sub' => $newUser->id,
'iat' => time(),
'exp' => time() + 300,
];
if (!in_array($this->request->getData('st'), PpState::getActiveStateAbbreviations())) {
$json = [
'success' => false,
'message' => 'Oh, bother! Poppins Payroll does not yet operate in your state. We’ve made note of your location, so we know where we’re needed. We look forward to being able to serve you soon.',
];
} else {
$json = [
'success' => true,
'token' => JWT::encode($payload, $privateKey, 'HS256'),
];
}
} else {
$json = [
'success' => false,
'message' => 'Issue in user registration',
];
}
}
$this->set(compact('json'));
$this->viewBuilder()->setOption('serialize', 'json');
}
public function login()
{
$result = $this->Authentication->getResult();
if ($result->isValid()) {
$privateKey = file_get_contents(CONFIG . '/jwt.key');
$user = $result->getData();
$payload = [
'iss' => 'myapp',
'sub' => $user->id,
'iat' => time(),
'exp' => time() + 60,
];
$json = [
'success' => true,
'token' => JWT::encode($payload, $privateKey, 'HS256'),
];
} else {
$this->response = $this->response->withStatus(401);
$json = [];
}
$this->set(compact('json'));
$this->viewBuilder()->setOption('serialize', 'json');
}
}
Postman API calls
I am looking for CakePHP 4 Authorization issue to solve while implementing JWT token bases APIs
The problem is the order in which you load the authenticator in your Application.php.
You should load your Jwt first and then the Form authenticator.
$service->loadAuthenticator('Authentication.Jwt', [
'secretKey' => Security::getSalt(),
'returnPayload' => false
]);
$service->loadAuthenticator('Authentication.Form', [
'fields' => $fields,
'loginUrl' => '/users/login'
]);

Automatic Authentication using Grafana API

In my web application, I want to provide the ability to pass authenticated users from my dashboard across to Grafana.
Once a user logged in my dashboard using credentials, a link to Grafana Dashboard will be displayed on my application. When user clicks that link, he/she will be redirected to Grafana page and automatically log in without displaying the Grafana login page. I don't want my users must encounter a second login screen, where they will be confused as to what username/password to enter.
I've followed Automatic login to grafana from web application, Auto login to grafana dashboard, Auto login to grafana from Web application using credentials or token
and Automatic login by token url, but no luck. I couldn't find appropriate & clean solution.
I'm using Grafana v6.2.5 installed on Ubuntu Server 18.04.
How can I implement it? Any help would be appreciated.
Server Details: Ubuntu Server 18.04, Apache 2.4.29
After some digging, I've found a workaround using Grafana's Generic OAuth Authentication.
Step 1: Create files with the following code in it.
GrafanaOAuth.php:
<?php
declare(strict_types=1);
class GrafanaOAuth
{
protected $user;
/**
* Create a new GrafanaOAuth instance.
* #param array $user
* #return void
*/
public function __construct(array $user)
{
$this->user = $user;
}
/**
* Redirect to authentication URL.
* #param string $state
* #return void
*/
public function auth(string $state): void
{
$state = urlencode($state);
$url = "http://localhost:3000/login/generic_oauth?state={$state}&code=cc536d98d27750394a87ab9d057016e636a8ac31";
header("Location: {$url}");
}
/**
* User access token.
* #return void
*/
public function token(): void
{
$token = [
'access_token' => $this->user['access_token'],
'token_type' => 'Bearer',
'expiry_in' => '1566172800', // 20.08.2019
'refresh_token' => $this->user['refresh_token']
];
echo json_encode($token);
}
/**
* User credentials.
* #return void
*/
public function user(): void
{
$user = [
'username' => $this->user['username'],
'email' => $this->user['email']
];
echo json_encode($user);
}
}
oauth/auth.php:
<?php
declare(strict_types=1);
require __DIR__ . '/../GrafanaOAuth.php';
/**
* Fetch the details of Grafana user from your database.
*/
$user = [
'username' => 'nbayramberdiyev',
'email' => 'nbayramberdiyev#outlook.com',
'dasboard_id' => 'oNNhAtdWz',
'access_token' => md5(uniqid('nbayramberdiyev', true)),
'refresh_token' => md5(uniqid('nbayramberdiyev', true))
];
(new GrafanaOAuth($user))->auth($_GET['state']);
oauth/token.php:
<?php
declare(strict_types=1);
header('Content-Type: application/json');
require __DIR__ . '/../GrafanaOAuth.php';
/**
* Fetch the details of Grafana user from your database.
*/
$user = [
'username' => 'nbayramberdiyev',
'email' => 'nbayramberdiyev#outlook.com',
'dasboard_id' => 'oNNhAtdWz',
'access_token' => md5(uniqid('nbayramberdiyev', true)),
'refresh_token' => md5(uniqid('nbayramberdiyev', true))
];
(new GrafanaOAuth($user))->token();
oauth/user.php:
<?php
declare(strict_types=1);
header('Content-Type: application/json');
require __DIR__ . '/../GrafanaOAuth.php';
/**
* Fetch the details of Grafana user from your database.
*/
$user = [
'username' => 'nbayramberdiyev',
'email' => 'nbayramberdiyev#outlook.com',
'dasboard_id' => 'oNNhAtdWz',
'access_token' => md5(uniqid('nbayramberdiyev', true)),
'refresh_token' => md5(uniqid('nbayramberdiyev', true))
];
(new GrafanaOAuth($user))->user();
custom.js:
$(function() {
'use strict';
if (location.pathname === '/login') {
location.href = $('a.btn-service--oauth').attr('href');
}
});
Step 2: Edit Grafana configuration file which is located at /etc/grafana/grafana.ini on Ubuntu / Debian, /usr/local/etc/grafana/grafana.ini on MAC, <GRAFANA_PROJECT_FOLDER>/conf/custom.ini on Windows.
Uncomment these lines and enter your client_id, client_secret, auth_url, token_url, api_url:
#################################### Generic OAuth ##########################
[auth.generic_oauth]
;enabled = true
;name = OAuth
;allow_sign_up = false
;client_id = some_id
;client_secret = some_secret
;scopes = user:email,read:org
;auth_url =
;token_url =
;api_url =
Like so:
#################################### Generic OAuth ##########################
[auth.generic_oauth]
enabled = true
name = OAuth
allow_sign_up = false
client_id = YOUR_APP_CLIENT_ID
client_secret = YOUR_APP_CLIENT_SECRET
scopes = user:email,read:org
auth_url = http://foo.bar/oauth/auth.php
token_url = http://foo.bar/oauth/token.php
api_url = http://foo.bar/oauth/user.php
Step 3: Place custom.js in /usr/share/grafana/public/build/index.html file (Ubuntu / Debian) at the bottom of <body> tag.
Step 4: Restart Grafana server.
sudo service grafana-server restart (Ubuntu / Debian)
brew services restart grafana (MAC)
For the example and detailed explanation, have a look at my Github repo.

Trying to get Laravel Dusk to behave with sqlite database

I'm trying to get Laravel Dusk to play nicely with an App i'm trying to test.
At the moment I can write to a test sqlite database but when I try to test a login form following the guidance it appears the details in the development database are being used instead.
Here's my test:
class LoginTest extends DuskTestCase
{
private $user;
use DatabaseMigrations;
public function setUp()
{
parent::setUp();
$this->user = factory(User::class)->create(['password' => bcrypt('secret')]);
}
/**
* A Dusk test example.
*
* #return void
* #throws \Exception
* #throws \Throwable
*/
public function test_user_can_log_in()
{
$this->browse(function (Browser $browser) {
$browser->visit('/login')
->assertSee('Members sign in')
->type('email', $this->user->email)
->type('password', 'secret')
->driver->executeScript('window.scrollTo(0, 500);');
$browser->press('Sign in')
->assertPathIs('/home');
});
}
}
This test fails authentication as the user I've just created doesn't exist in the development Mysql database it is reading from.
I am able to see the user I've just created in the sqlite database and can query that user exists
What am I doing wrong? Does Laravel Auth do something to override the connections?
Thank you
edit
Here is my .env file
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=backend_cms
DB_USERNAME=homestead
DB_PASSWORD=secret
DB_DATABASE_2=members
DB_USERNAME_2=homestead
DB_PASSWORD_2=secret
and my .env.dusk.local (I've also tried renaming to just .env.dusk but no change.
DB_CONNECTION=sqlite_testing
DUSK=true
I read that only the items you need changing should be there so assumed only the connection required?
edit
Here's the config entries in database.php
'sqlite' => [
'driver' => 'sqlite',
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
],
'sqlite_testing_memory' => [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
],
'sqlite_testing' => [
'driver' => 'sqlite',
'database' => database_path('database.sqlite'),
'prefix' => '',
],

Authentication using username instead of email laravel 5.2

Below is my code for AuthController
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
//use App\Http\Requests\Request;
use Request;
use View;
use Hash;
use DB;
use Auth;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/home';
protected $redirectAfterLogout = '/login';
protected $username = 'user_name';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
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',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
public function showLogin()
{
if (Auth::check())
{
return redirect('/home');
}
else
{
return View::make('index');
}
}
public function doLogin()
{
//echo 'test';
$input = Request::all();
$pass = Hash::make($input['password']);
//print_r($input);exit;
//echo $input['username'];exit;
/*DB::table('admin_user')->insert(
['user_name' => $input['username'], 'password' => $pass]
);*/
if (Auth::attempt(['user_name' => $input['username'], 'password' => $input['password']])) {
return redirect('/home');
//return View::make('home');
}
else
{
return redirect('/');
}
}
public function doLogout()
{
Auth::logout();
return redirect('/');
}
}
Below is my Route Code
Route::get('/',array('uses'=>'Auth\AuthController#showLogin') );
Route::post('/login',array('uses'=>'Auth\AuthController#doLogin'));
//Route::get('/login',array('uses'=>'Login#showLogin') );
Route::group(['middleware' => ['web', 'auth.basic']], function(){
Route::get('/home',['uses'=>'Home#getHome']);
Route::get('/logout',array('uses'=>'Auth\AuthController#doLogout') );
});
i am using user name instead of email id for Auth but below error is shown
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'email' in
'where clause' (SQL: select * from admin_user where email = admin
limit 1)
below is my kernal.php code
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
}
please help me how can i do login with username .
Thanks in advance.
Update:
Add the auth middleware to specific route
Route::group(['middleware' => ['web']], function(){
Route::get('/',array('uses'=>'Auth\AuthController#showLogin') );
Route::post('/login',array('uses'=>'Auth\AuthController#doLogin'));
Route::get('/home',['uses'=>'Home#getHome'])->middleware('auth');//update
Route::get('/logout',array('uses'=>'Auth\AuthController#doLogout') );
});
To redirect to intended page after login replace your doLogin() function with following:
public function doLogin()
{
$input = Request::all();
$pass = Hash::make($input['password']);
if (Auth::attempt(['user_name' => $input['username'], 'password' => $input['password']])) {
return redirect()->intended('/home');//This line is changed
}
else
{
return redirect('/');
}
}
Explaination:
intended() method redirects the user to the previous page, from where the user is redirected to login page. It expects a default route as a parameter, where user will be sent if he has came here directly.
Update 2:
add doLogout in your AuthController's constructor:
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'doLogout']);
}
You can simply override $username in AuthController by writing protected $username = 'username'.

How to login user using rest api in yii2

I new in yii2, I want login user using rest api but unable to do this.I have setup basic REST API From This blog:
budiirawan.com/setup-restful-api-yii2/
After that I have created :
api\modules\v1\controllers\SiteController.php
<?php
namespace api\modules\v1\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use common\models\LoginForm;
use yii\filters\VerbFilter;
use yii\rest\ActiveController;
/**
* Site controller
*/
class SiteController extends ActiveController
{
/**
* #inheritdoc
*/
public $modelClass = 'api\modules\v1\models\user';
public function actionIndex()
{
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
return $this->render('login', [
'model' => $model,
]);
}
}
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
}
And Created Model
RtWorkForce\api\modules\v1\models\User.php
<?php
namespace api\modules\v1\models;
use \yii\db\ActiveRecord;
/**
* User Model
*
*/
class User extends ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return '{{%user}}';
}
}
Here Is my main.php
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-api',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'modules' => [
'v1' => [
'basePath' => '#app/modules/v1',
'class' => 'api\modules\v1\Module'
]
],
'components' => [
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
],
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => false,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => ['v1/country','v1/user','v1/site'],
'tokens' => [
'{id}' => '<id:\\w+>'
]
]
],
]
],
'params' => $params,
];
But IT's not working i don't know where i am wrong ??
From Yii 2.0 REST Authentication docs :
Unlike Web applications, RESTful APIs are usually stateless, which
means sessions or cookies should not be used.
And from this other docs about the user class which implement yii\web\IdentityInterface :
if your application is a pure stateless RESTful application, you would
only need to implement findIdentityByAccessToken() and getId() while
leaving all other methods with an empty body.
RESTfull is about routing. If following a token based authentication, then, It should return a resources or a collections if the request sent to server is holding a valid token. Otherwise it should be rejected.
Login process in that case, is one request holding a username/password pair that will be exchanged with a valid token by server, that is the token you are going to include with all your next requests.
If session is disabled on server side by setting enableSession to false as described in Yii documentation (see links above) and as recommended by the stateless nature of REST, then \Yii::$app->user->isGuest should not provide info as your server won't have any session to get it from. (unless it verifies token validity instead of checking session)
When building a class extending yii\rest\ActiveController you can't render a html page like :
return $this->render('login', [
'model' => $model,
]);
or redirect to a different HTML page like :
return $this->goHome();
That will work with a yii\base\Controller when building a HTML based web app instead of yii\rest\ActiveController. with ActiveController you just return data which will be serialized to json or xml before output.
Please refer to Yii RESTful API framework documentations for more details. Then you may find useful information in this great tutorial on How to implement Yii2 REST Authentication :
http://blog.neattutorials.com/angularjs-and-yii2-part-2-authentication/