How to secure a Lithium php RESTful API? - php

I have created a RESTful apps using Lithium php framework and now my question is how to secure it?
Is there any existing code for OAUTH or HTTP Digest Authentication that uses lithium framework?

Thanks for editing your question to actually ask something specific. Please see the following:
https://github.com/search?q=li3_oauth
http://li3.me/docs/lithium/security/auth/adapter/Http

While I'm not sure what sort of security you are looking for ...
There is built in security for Lithium, you can see two short tutorials to get you going here:
Simple Authentication in Lithium
Creating a user in M, V, C
The basics are covered in the "Simple Authentication" tutorial ... you'll need:
A database to keep track of you users
Bootstrap Auth via config/bootstrap.php
Setup Sessions & Auth adapters
Then it depends on if you are going to do authenticaion via forms, or by some other method.
The turtorials will show you how to setup a form, but you can also "secure" the route (url) that is being requested via the config/routes.php file like so ...
<?php
use lithium\net\http\Router;
use lithium\core\Environment;
use lithium\security\Auth;
// check if the user is logged in
$user = Auth::check('default');
// these routes are not behind a login
Router::connect('/login', 'Sessions::add');
Router::connect('/logout', 'Sessions::delete');
if ($user && $user["user"] == "admin") {
// these two routes will only work if a user is authenticated.
Router::connect('/{:controller}/{:action}/{:args}.{:type}');
Router::connect('/{:controller}/{:action}/{:args}');
}
// redirect the user to a login if no other routes match
Router::connect('/{:args}', array(), function($request) { header('Location: /login/url/'.str_replace('/','*',$request->url)); exit; });
?>

Related

Laravel Auth external data for login and register

I am using the Laravel 5.2 Auth system coming up with this command :
php artisan make:auth
Although this works totally fine as is, my goal is to use an external API to perform login, registering and changing password while still being able to use the core function of the Auth class.
So taking the login for example, I want to use something like
function login(ApiController $api) {
// This function return data or error code and message in JSON
$login = $api->login([ $credentials['email'], $credentials['password']]);
if($login->success)
// login successfully like normal Auth would do
else
// redirect to main page with $login->message
}
By the way, I want to pass fields coming up from $login to the Auth class, like we can actually do Auth::user()->email giving us the email, I'd want to set value like "database field" but with my API JSON fields behind
I looked on the Internet and found something to do inside AuthController and something related to ServiceProvider, but I don't know how to follow my exact needs
Adding a custom user provider would help in this case. There is no need to play with AuthController here. Check this Laravel Docs page.
You will need to create a new User Provider which implements Illuminate\Contracts\Auth\UserProvider, specify it in AuthServiceProvider and update your auth config file accordingly.
Here are the links to the framework's default User Providers for reference :
1) DatabaseUserProvider
2) EloquentUserProvider
I ended up coding my own Auth system...
Using session() and Input()

Codeingiter - RESTful API Key auth for only certain Routes

I'm in the process of building a RESTful API server. Everything is working as it should be as of now.
I'm using Phil Sturgeon RESTful server implementation for CodeIgniter which is pretty much popular.
https://github.com/chriskacerguis/codeigniter-restserver
What i need is to have a Basic API key authentication for some of the routes which this Package already provides, but it does apply to all the API Routes.
I do not want Authentication for all Routes..as some API should be called without Authentication
How do we achieve it..
Note : I cant switch the technology or framework as I'm currently using the Models which have been developed before and being used now.
Eg Route without Auth : $route['api/products'] = "api/Products/allProducts";
Eg Route with Auth : $route['api/devices/update'] = "api/Devices/updateDevice";
Try with:
$config['auth_override_class_method']['products']['allproducts'] = 'none';
$config['auth_override_class_method']['devices']['updatedevice'] = 'basic';
add the following code to "application/config/rest.php"
$config['auth_override_class_method']['Products']['allProducts'] = "none";
$config['auth_override_class_method']['Devices']['updateDevice'] = FALSE;
or you can just add this.
$config['auth_override_class_method']['Products']['allProducts'] = "none";
because your application automatically activates the token / is false so there is no need to add a route that activates the token again.

Authenticate a user using Laravel functions for an Android application

I am wanting to create an Android / iPhone application to enable mobile phone users to have the same functionality as the website.
The website's authentication works as planned:
Auth::attempt(array('email'=>Input::get('email'), 'password'=>Input::get('password')))
What I have is another auth.php within the public/app/ folder (I will add the .htaccess later!) that will authenticate users logging in through their mobile phones. Ideally, to make it simpler, I'm wanting to use all of the Laravel controller functions that my web app uses.
I know the Auth:: function resides in the BaseController but I'm unsure of how to access this within the /public folder, or if this is it the suggested method.
As anyone else authenticated a user through their mobile phone through Laravel?
Any help would be hugely appreciated. Many thanks.
I would suggest to create a route in the app/routes.php for authenticate a mobile user.
Route::post('mobile/auth', function() {
// your stuff
});
or via controller:
// app/routes.php
// connect the route to a controller
Route::post('mobile/auth', 'MobileAuthController#auth');
class MobileAuthController extends BaseController
{
public function auth()
{
// ...
}
}
Is this what you mean? or else i misunderstand you.
You're authentication is pretty basic, checkout the damn good documentation on the laravel website for better examples.

CakePHP Stateless (Basic) Auth, where to call $this->Auth->login()?

My CakePHP v2.4.X app supports both Basic and Form authentication (Form is for web users, and Basic is for Stateless access from Android App).
AppController.php contains the following $components declaration:
public $components = array(
'Auth' => array(
'authenticate' => array(
'Basic',
'Form',
),
),
);
From the doc on performing stateless Basic Auth:
"In your login function just call $this->Auth->login() without any checks for POST data."
My issue is that if the user logs in using Basic Auth, they never trigger Users/login - so I am unsure where to place the $this->Auth->login() function.
Do I simply place this code in AppController/beforeFilter() and if the current user is not logged in I attempt login every time? ie:
if($this->Auth->loggedIn() == false)
{
$this->Auth->login();
}
This doesn't seem right to me because if the user is using Form login they'll end up calling $this->Auth->login(); twice [once from AppController/beforeFilter(), and again from UsersController/login()].
Also, when simply loading the login (via GET), the system will attempt to log them in and therefore return an error message.
I am also unsure how to determine if the user did login via Basic (as opposed to Form), and therefore set: "AuthComponent::$sessionKey" to false only when Basic was used.
Any help would be much appreciated.
The manual section related to basic auth doesn't correspond to what you are saying. Since 2.4 basic/digest auth doesn't need a login action at all. Just including Basic in the array for "authenticate" key for auth config is enough. It will automatically cause cake to check for required credentials when trying to access a protected action and if no credential or invalid credentials are provided appropriate headers are returned to the client.
Using both Basic and Form authenticators together can be problematic. I suggest modifying auth config in beforeFilter to use only either one of them conditionally by using appropriate conditions to check if request is from mobile app or not.

method specific authentication in Phil Sturgeons php codeigniter rest api

Hi
I know that I can set the rest authentication in Phil Sturgeons rest API, but I only want authentication for some methods in the REST API.
I want some of my methods to be accessible for everyone with no authentication at all, and others to only be accessible to administrators/people authenticated users.
In .net I can simply set a [RequiresAuthentication] attribute over methods in a webservice, is there something similar I can do with Rest PHP in CodeIgniter?
Or Controller specific would be fine too.
"philsturgeon Phil Sturgeon
Why do people ask questions about my code on StackOverflow and random forums instead of just asking me?"
Go ask Phil Sturgeon.
Hello Jakob :) What you are trying to do is a bit tricky as Phil Sturgeons rest API Controller only supports setting the authentication method globally. To set it globaly you edit this line in the rest config file:
$config['rest_auth'] = '';
I have an untested theory though:
To set this setting per controller make sure the setting in the config file is as above (empty) and add this constructor to the controller you would like to specify authentication method for:
function __construct()
{
$this->load->config('rest');
//$this->_prepare_basic_auth(); //Uncomment to use basic
//$this->_prepare_digest_auth(); //Uncomment to use digest
parent::Controller();
}

Categories