Laravel - authenticating with session token - session

Upon login, I return the user object + session token in JSON form, so that the mobile device that connects to my application can be authenticated.
However, I have a difficulty understanding how would I go about authenticating the user only with his session id?
Once logged in, the mobile device sends the session token upon every request, which means I somehow need to check whether it's the same user (using a custom auth filter).
How would I do it?

You may have a table for saving tokens
Add a filter in routes.php
Route::group(array('before' => 'auth'), function() { ... })
And in the filters.php you can search the token in the database, if isn't exist you return a no access response
Route::filter('auth', function () {
$input_token = Input::get('token');
if (!empty($input_token)) {
$validator = Validator::make(
['token' => $input_token],
['token' => 'token']
);
if (!$validator->fails()) {
$token = Token::where('hash', $input_token)->first();
if ($token) {
$user = User::find($token->user_id);
if ($user) {
Auth::login($user);
return;
}
}
}
}
$response = Response::make(json_encode([
'error' => true,
'messages' => [
Lang::get('errors.NO_ACCESS')
]
]), 200);
$response->header('Content-Type', 'application/json');
return $response;
});

You could do it like this:
$sessionID = '4842e441673747d0ce8b809fc5d1d06883fde3af'; // get this from \Session::getId(); from your previous authenticated request (after logging in because it changes).
$s = new \Illuminate\Session\Store(NULL, \Session::getHandler(), $sessionID);
$s->start();
$userID = $s->get('login_82e5d2c56bdd0811318f0cf078b78bfc');
\Session::set('login_82e5d2c56bdd0811318f0cf078b78bfc', $userID);
return \Auth::user();
Not the prettiest code but it works. It creates an instance of a session using the previous Session ID, then start loads it up from file. The user ID is in that key, so then it just sets the user id on the current session. Then when you call Auth::user() it loads up the User using that user id.
The reason for all the numbers in the key is because the larval developer thought it would be smart to hash the Auth class name to make the key as unique as possible... :-S

Related

Create session on consuming login with api on laravel

I have an api that has a method to start and I am calling it from a frontend project.
In the front end project I use Guzzle to make the call via post to the api and login, from which I get back a json with the user data and a jwt token.
But when I receive the token as I manage the session, I must create a session and save the token, since the laravel to authenticate I need a model user and have a database, which of course I do not have in this backend because I call the api to log in, which brings a token and user data, then as I manage it from the backend, I'm a little lost there.
$api = new Api();
$response = $api->loginapi(['user'=>'wings#test.com','password'=>'123']);
Because here I could not do Auth::login($user) to generate the session.
Because I don't have here the database because the login is done from the api.
There I call the api, of which the answer is the token, but how do I manage it from here, creating a session? saving the token?
thanks for your help.
With api, you don't usually manage a session. usually, you'd call something like
Auth::attempt([
'email' => 'me#example.com',
'password' => 'myPassword'
]);
If the credentials are correct, laravel will include a Set-Cookie header in response, and, that is how you authenticate with api. Via an auth cookie. You don't need to do anything else.
Let's show you how:
//AuthController.php
public function login(Request $request) {
$validatedData = $request->validate([
'email' => 'required|email',
'password' => 'required'
]);
if(Auth::attempt($validatedData)){
return ['success' => 'true'];
}
else{
return ['success' => false, 'message' => 'Email or password Invalid'];
}
}
public function currentUser (){
return Auth::user();
}
Now, the APi file
Route::post('/login', ['App\Http\Controllers\AuthController', 'login']);
Route::get('/current_user', ['App\Http\Controllers\AuthController', 'currentUser']);
Now if you make a call to /api/current_user initially, you'll get null response since you're not currently logged in. But once you make request to /api/login and you get a successful response, you are now logged in. Now if you go to /api/current_user, you should see that you're already logged in.
Important ::
If you are using fetch, you need to include credentials if you're using something other than fetch, check out how to use credentials with that library or api
You want to use the API to authenticate and then use the SessionGuard to create session including the remember_me handling.
This is the default login controller endpoint for logging in. You don't want to change this, as it makes sure that user's do not have endless login attempts (protects for brut-force attacks) and redirects to your current location.
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)) {
if ($request->hasSession()) {
$request->session()->put('auth.password_confirmed_at', time());
}
return $this->sendLoginResponse($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);
}
The core happens when we try to "attemptLogin" at
protected function attemptLogin(Request $request)
{
return $this->guard()->attempt(
$this->credentials($request), $request->boolean('remember')
);
}
When using the SessioGurad (which is default) the method attemptLogin fires a couple of events, checks if the user has valid credentials (by hashing the password and matching it with db) and then logs the user in, including the remember me functionality.
Now, if you don't care about events, you can just check from your API if the credentials match and then use the login method from the guard. This will also handle the remember me functionality. Something like this:
protected function attemptLogin(Request $request)
{
$username = $request->input($this->username());
$password = $request->input('password');
$result = \Illuminate\Support\Facades\Http::post(env('YOUR_API_DOMAIN') . '/api/v0/login' , [
'username' => $username,
'password' => $password
])->json();
if(empty($result['success'])){
return false;
}
// Maybe you need to create the user here if the login is for the first time?
$user = User::where('username', '=', $username)->first();
$this->guard()->login(
$user, $request->boolean('remember')
);
return true;
}

Laravel Stormpath not able to access User Object

I am using Laravel and Stormpath for User Management. I am able to register and login user successfully using AJAX.
After successful login only the url is returned to AJAX, but after login when I go to User specific pages I am not able to fetch User Data.
Registration and Login happens in RegisterController
User Pages are rendered using UserController
I've tried to get User data using
$user = app('stormpath.user');
in UserController, but when I do dd($user) null is returned.
How to persist or get User Data after successful login or sign-up in other Controllers?
Any help appreciated! Thanks in advance!
For the Stormpath Laravel integration, when you run AJAX calls, we do not set any cookies. We provide you with the JWT in the header response that you will need to look at and then store them youself. The JWT will then need to be attached to all other requests as a Bearer token which will allow you to use the `$user = app('stormpath.user') method to get the user information out of the JWT.
I finally got everything working. Thank you #bretterer
// Stormpath user account creation
\Stormpath\Client::$apiKeyProperties = "apiKey.id="
.env('STORMPATH_CLIENT_APIKEY_ID').
"\napiKey.secret=".env('STORMPATH_CLIENT_APIKEY_SECRET');
$client = \Stormpath\Client::getInstance();
$apps = $client->tenant->applications;
$apps->search = array('name' => 'My Application');
$application = $apps->getIterator()->current();
$account = \Stormpath\Resource\Account::instantiate(
[
'givenName' => $request->input('username'),
'middleName' => '',
'surname' => 'StromTrooper',
'username' => $request->input('username'),
'email' => $request->input('user_mail'),
'password' => $request->input('user_pass'),
'confirmPassword' => $request->input('user_pass')
]
);
// Create User Account and Log-in the User
try
{
$response = $application->createAccount($account);
$passwordGrant = new \Stormpath\Oauth\PasswordGrantRequest(
$request->input('user_mail'),
$request->input('user_pass')
);
$auth = new \Stormpath\Oauth\PasswordGrantAuthenticator($application);
$result = $auth->authenticate($passwordGrant);
$atoken = cookie("access_token",
$result->getAccessTokenString(),
$result->getExpiresIn()
);
$rtoken = cookie("refresh_token",
$result->getRefreshTokenString(),
$result->getExpiresIn()
);
$response_bag['success'] = url('userprofile');
}
catch (\Stormpath\Resource\ResourceError $re)
{
$response_bag['error'] = $re->getMessage();
$atoken = 'null';
$rtoken = 'null';
}
return response()
->json($response_bag)
->withCookie($atoken)
->withCookie($rtoken);
and in the User controller I am able to access the user details using app('stormpath.user');
and since I was using Laravel 5.1
I had to comment out $token = $request->bearerToken(); from vendor/stormpath/laravel/src/Http/Middleware/Authenticate.php from function public function isAuthenticated(Request $request)

Codeigniter 3 login check function not showing correct flashdata messages

I am creating a login check function. But my two flash data messages are not setting correct.
If user has logged on and then if the session expires it should set this
flash data message Your session token has expired!
And if the user has not logged on and tries to access a controller with out logging on
then it should set this flashdata message You need to login to
access this site!
For some reason it is always showing the second flashdata message.
Question: How am I able to use the two flashdata messages properly.
Controller: Login.php
Function: check
public function check() {
$uri_route = basename($this->router->directory) .'/'. $this->router->fetch_class();
$route = isset($uri_route) ? $uri_route : '';
$ignore = array(
'common/login',
'common/forgotten',
'common/reset'
);
if (!in_array($route, $ignore)) {
// $this->user->is_logged() returns the user id
if ($this->user->is_logged()) {
// $this->session->userdata('is_logged') returns true or false
if (!$this->session->userdata('is_logged')) {
// Redirects if the user is logged on and session has expired!
$this->session->set_flashdata('warning', 'Your session token has expired!');
redirect('admin/common/login');
}
} else {
$this->session->set_flashdata('warning', 'You need to login to access this site!');
redirect('admin/common/login');
}
}
I run function via codeigniter hook that way I do not have to add it on every controller.
$hook['pre_controller'] = array(
'class' => 'Login',
'function' => 'check',
'filename' => 'Login.php',
'filepath' => 'modules/admin/controllers/common'
);
What are you trying to check via the uri() is actually a very bad way of checking, also you should include login checks as a construct function not single.. here is what your function should look like:
function __construct()
{
parent::__construct();
if (!$this->session->userdata('logged_in')) {
// Allow some methods?
$allowed = array(
'some_method_in_this_controller',
'other_method_in_this_controller',
);
if (!in_array($this->router->fetch_method(), $allowed)
{
redirect('login');
}
}
}

laravel login with google account

I am making an application and I want users to login with their google account. I have user oauth-4-laravel and I have this:
UserController.php
// get data from input
$code = Input::get('code');
// get google service
$googleService = Artdarek\OAuth\Facade\OAuth::consumer("Google");
if (!empty($code)) {
// This was a callback request from google, get the token
$token = $googleService->requestAccessToken($code);
// Send a request with it
$result = json_decode($googleService->request('https://www.googleapis.com/oauth2/v1/userinfo'), true);
$user = DB::select('select id from users where email = ?', array($result['email']));
if (empty($user)) {
$data = new User;
$data->Username = $result['name'];
$data->email = $result['email'];
$data->first_name = $result['given_name'];
$data->last_name = $result['family_name'];
$data->save();
}
if (Auth::attempt(array('email' => $result['email']))) {
return Redirect::to('/');
} else {
echo 'error';
}
}
// if not ask for permission first
else {
// get googleService authorization
$url = $googleService->getAuthorizationUri();
// return to facebook login url
return Redirect::to((string) $url);
}
}
After this i get successfully user info and can save user name, in my database. The problem is that after this I want to redirect user to home page and can't do this because with normal login i chec authentication:
if (Auth::attempt(array('email' => Input::get('email'), 'password' => Input::get('password')))) {
return Response::json(["redirect_to" => "/"]);
and with google login i get onlu username , user id and email. How to login directly the user after google login?
If you need to log an existing user instance into your application, you may simply call the login method with the instance:
$user = User::find(1);
Auth::login($user);
This is equivalent to logging in a user via credentials using the attempt method.
For further info see: http://laravel.com/docs/security#manually

Laravel, log in user for one request

I am building a REST API with Laravel, and I have a filter that checks for a TOKEN:
Route::filter('api.auth', function() {
$token = Request::header('X-CSRF-Token') ? Request::header('X-CSRF-Token') : '';
if (empty($token)) {
return Response::json(
['message' => 'A valid API key is required!'],
401
);
};
$user = User::where('token', '=', $token);
if ($user->count()) {
$user = $user->first();
Auth::login($user);
} else {
return Response::json(
['message' => 'Your token has expired!'],
401
);
};
});
If everything is ok, the filter will log in the user with uth::login($user);
How can I log him for only 1 request?
Since this filter is going to be checked on every request, I think it would be better to log the user out each time.
I have seen this in Laravel's docs, not sure how to apply it:
if (Auth::once($credentials))
{
//
}
Could I have a callback in my response? where I could log the user out?
/*
Get all products.
*/
public function getProducts() {
$products = Auth::user()->products;
return Response::json($products, 200);
}
Any ideas?
If you haven't user's password use this:
if(Auth::onceUsingId($userId)) {
// do something here
}
If I correctly understand the question then I would say that, just replace following
Auth::login($user);
with this (To log the user in only for current request):
Auth::once(['email' => $user->email, 'password' => $user->password]);
If you log in a user only for once then you don't have to manually logo out the user, the user will be asked again for to log in on next request.

Resources