I trying to use lumen for the first time to create a restful backend service.
I'm used to working with laravel but with lumen I'm already stuck at the autentication. I can't find any tutorials on this.
I'm not even sure if my logic is secure for this. Bassically I receive a post request which contains an email and a password, then I want to check if the details are correct etc and authenticate the user.
I feel like I'm missing something, is this something that lumes comes with standard or will I need to rewrite the Auth service
It seems to be in the documentation you linked.
$this->app['auth']->viaRequest('api', function ($request) {
// Return User or null...
});
The Request class is passed in to this function. You would need to grab the email and password out of it $request->get('email') and request->get('password'), check to make sure they are valid.
I'm not sure of the best way to do this with Lumen or how much is available so to make it easy, you could just do something like the following...
$this->app['auth']->viaRequest('api', function ($request) {
$email = $request->get('email');
$password = $request->get('password');
$user = \DB::table('users')->where('email', $email)->first();
// Invalid Email
if ($user === null) {
return null;
}
// Check if password matches
if ( \Hash::check($user->password, $password) ) {
return $user;
}
// Invalid password
return null;
});
Keep in mind Lumen does not support session state you would need to pass in the email and password for every request. However, once it's setup, all you need to do in Lumen is use Auth::user() to grab the user.
You could also use jwt-auth which uses JSON Web Tokens which also makes it fairly easy and allows you to not pass emails and password around.
https://github.com/tymondesigns/jwt-auth
For anyone who encounters this problem. This is how i solved it:
In the auth serviceProvider (boot method) you check if there is a authorization header present. If there is one, it should include a apiToken, witch you can validate and continue with the normal flow.
If there is no Authorization header present, you can check the request variable for a email and password. Validate the login, and on success you save a new apiToken. I returned this token to the frontend, and made a feature that handles all ajax request, to include this token in the header. I also implemented a function that handles every response in my frontend application witch checks for a 401, when its there redirect to the login page.
With this aproach, you can use both auth methods, and Auth::user() is available through your application. Just make sure the login page is not handled with the Auth middleware!
Related
I am currently doing a website wherein the login URLs are varying and displays the data according to the assigned projects to them.
For example, user A can only access www.example.com/projects/proj1. This is the homepage for user A and if he logs in he uses www.example.com/projects/proj1/login
While user B can only access www.example.com/projects/proj2. This is the homepage for user B and if he logs in he uses www.example.com/projects/proj2/login
Please note that proj1 and proj2 are varying depending on the database. So I have to check first that these projects are already registered in the database.
I am thinking of having a route like this.
For web.php
Route::get('/projects/{project_name}', 'PageHandler\CustomPageController#projects');
Route::get('/projects/{project_name}/login', 'PageHandler\CustomPageController#login');
Route::put('/projects/{project_name}/auth/{user}', 'PageHandler\TestUserPageController#auth');
Then my customepagecontroller.php looks like this
class CustomPageController extends Controller
{
public function projects(string $projectName)
{
if (auth()->user() == null)
return redirect('/projects'. '/' . $projectName . '/login');
}
public function login(string $projectName)
{
return view('login')->with('projectName', $projectName);
}
public function auth(Request $request, string $projectName)
{
$username = $request->username;
//How to set $username as logged in?
// rest of the code to show the home page after authentication
}
}
login.blade.php basically just looks like a form submitting username and password and calling auth of CustomPageController with a string parameter for the URL
So my question is how can I set $username as logged in already using the Auth of Laravel? Or should I create my custom Authentication Controllers?
Now, this is the only approach I have in mind for me to enable the logging in of users to varying URLs. Please let me know if you have better approach.
Thank you!
If you only want to limit the project the users can access, I do not see a need to use 2 different login URLs (please correct me if there is a reason why you want different URLs for that), instead, you simply find which project the user belongs to from the database.
For authentication, Laravel allows you to implement authentication in a very easy way, you can refer to the documentation. Using Laravel's authentication would be easier and safer than writing your own one, and even if the default functionalities it provides may not be exactly the same as those you would want to achieve, you can still add your own things, which is still a lot easier than implementing it from scratch.
As for setting a user as logged in with Laravel's authentication services, you can use Auth::login($user);. Here, $user must be an implementation of the Illuminate\Contracts\Auth\Authenticatable contract. You can refer to this part of the documentation for more details.
I created a way to authenticate a user with API keys, thanks to a class A implementing the SimplePreAuthenticatorInterface interface. Everything works well (the user is successfully authenticated).
I'm trying to store the API keys, for a later use during the user's journey. To do so, inside the authenticate method of my class A, I return a PreAuthenticatedToken in which the credentials are my API keys.
The problem is : Inside a custom service, when I try to get the token credentials, I get null... I successfully get the API keys when I comment the line 76 of the PreAuthenticatedToken Symfony core class :
public function eraseCredentials()
{
parent::eraseCredentials();
//$this->credentials = null;
}
My questions are:
1) Why is the method eraseCredentials called whereas the user is authenticated? I thought this method was called during user's logging out...
2) What am I doing wrong? Is the PreAuthenticatedToken token the right place to store my API keys? How can I get them back from a custom service ?
Thanks for helping me. :)
PS : I'm a newbee on posting in Stackoverflow (and in English ^^). Sorry in advance for any mistakes.
I found another similar question but it has no helping response and I added some more precisions.
EDIT: The code of my custom service where I try to get the credentials is:
$token = $this->container->get("security.token_storage")->getToken();
if ($token !== null) {
$credentials = $token->getCredentials();
// $credentials is null here
}
EDIT 2: The return part in my code of my SimplePreAuthenticatorInterface::authenticateToken method :
return new PreAuthenticatedToken(
$user,
$apiKeys,
$providerKey,
$user->getRoles()
);
Ad 1. It depends on your AuthenticationProviderManager: this class accepts $eraseCredentials as second parameter - by default set to true (here).
That's why eraseCredentials method is being called on PreAuthenticatedToken $token during authenication (here).
Ad 2. Please check How to Authenticate Users with API Keys tutorial. You should create your custom ApiKeyAuthenticator class and add logic there.
According to your comment:
Note that authenticateMethod from tutorial is being called inside authenticate method (here). At that time token credentials are not erased yet and you can access them. For security reason they are erased after authentication (but this can also be changed / configured via security.yml file). If you need them later you can introduce custom token class and store API key there.
I am building a new Laravel application (v5.4) that will run alongside (installed in the same environment) an existing PHP application that has it's own authentication system. I want the users who have successfully logged in to the existing system to be automatically authenticated in the Laravel app so they can navigate seamlessly between the applications.
My Laravel app has read-only access (through a second db connection) to the existing system's database so it can safely check that the PHP Session matches the session cookie recorded in the database and I can even pull out the user object and hand it to Auth's login() method.
I want to know the best way to put Auth into an authorised state (not guest) and where is the best place to put such code?
Options I've thunked of so far:
Middleware: Check session and call the login() method on Auth from some application-wide middleware?
Extend Illuminate/Auth/SessionGuard.php and override the attempt() method? If so, how do I tell the other parts to use my extended SessionGuard? (I suspect this was not designed to be easily overridden)
Super hacky disgusting way of dynamically setting the user's password to a random hash and then calling Auth/LoginController#login() in the background with a faked request containing that hash as the password field. (I seriously hope this doesn't end up being the most popular answer)
Some other option (?)...
Thanks in advance for your help SO community!
The solution I ran with in the end was creating a middleware that contains this:
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if (isSet($_SESSION['intranet_user_id']) && $_SESSION['intranet_user_id']) {
// Log them in manually
$intranet_user_id = $_SESSION['intranet_user_id'];
if (!Auth::guest() && Auth::user()->getId() !== $intranet_user_id ) {
Auth::logout();
}
if (Auth::guest()) {
Auth::login( User::find($intranet_user_id), true);
}
} else {
Auth::logout();
}
I am creating an AngularJS application with a restful API written in PHP as backend. This is the first time I'm using AngularJS and PHP "together".
Angular is keeping track of the authentication of users using the ngCookies module. Some operations, like deleting stuff, should only be available for users with specific privileges. How can I make sure that "normal" users or users that have not logged in cannot access the deletion operations of the API?
Any ideas are appreciated.
Here is how I do it.
In users DB table I add column named token VARCHAR(36)
Whenever user logs in:
I update lastlogin column
I update that token with MD5($ip.$email.$logindate)
Now I return user object to Angular and angular knows token.
In Angular $http service I add interceptors and before any request is made Authentication header is set. I use basic authentication. I create string $user_id.'::'.$token.
app.factory('authInterceptor', function($rootScope, $q, appConfig, $injector, $cacheFactory) {
function request(config) {
if(angular.isDefined($rootScope.currentUser.id)) {
config.headers.Authorization = 'Basic ' +
window.btoa($rootScope.currentUser.id + ':' +
$rootScope.currentUser.token);
}
return config;
}
function response(response) {
if(angular.isDefined(response.data.code) && parseInt(response.data.code) == 401) {
var UserApi = $injector.get('UserApi');
UserApi.logout();
$cacheFactory.get('$http').removeAll();
UserApi.login(response.data.message)
.catch(function() {
var $state = $injector.get('$state');
$state.go('app.home');
});
}
return response || $q.when(response);
}
return {
request: request,
response: response
};
})
This is my authInterceptor factory that I insert into app
app.config(function($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
})
What is happening there I set standard Authentication header for every request if user is authorised.
Then in PHP I get this header. I get user ID and Token separately. Then I use user ID to get user data from DB where I have token and last login date.
Now I can compare token and see if this user is the one who logged in.
But this is not absolutely secure. If anyone get this token, then he can login. That is why IP is used. not only I check the token against one in DB I also check it against IP. I create MD5($ip.$email.$logindate) because I know all that data and check against token that I get from angular. If it was sent from different IP it will not pass through.
You can also see function response in authInterceptor. Whenever I have authentication problem I send back HTTP code 401. Now in response I know that Authentication failed. I logout user and redirect him to homepage of the site.
Now it is very simple to code. You just return what have to be returned, and do not care about none authenticated user.
But there is more. If you need some kind of ACL, then you can design this as you wish. In your class that return particular RESTFull API method you can define $acl property and set name of the group. In the same place where you check for authentication, you can check for ACL too.
Please see my code here it is PHP backend and Angular frontend
https://github.com/Coach-Hub
This is the basic Idea, you can of course build around that.
I am not a php developer. You can not ensure this thing in front-end-side. Below is the sample code we use in NodeJs app, to validate user has valid permission of deletion or not.
router.patch('/:id', auth.hasRole(userEnums.roles.admin), controller.update);
router.post('/create', auth.hasRole(userEnums.roles.admin), controller.create);
//Checks if the user role meets the minimum requirements of the route
function hasRole(roleRequired) {
if (!roleRequired) throw new Error('Required role needs to be set');
return compose()
.use(isAuthenticated())
.use(function meetsRequirements(req, res, next) {
if (req.user.role.indexOf(roleRequired) !== -1) {
next();
}
else {
res.send(403);
}
});
}
Here auth.hasRole is simple method/middleware, which is a curry design pattern. It checks use req and checks that user has valid permission to delete. In case of user don't have admin permission it return back with unautherize error message.
This is for admin and user relation. We also use another strategy at the end to validate user. Suppose we have expose our delete API and anyone can delete it. In that case we have to ensure that active user has to be the owner of the document. In that case first we get the owner id of the document and match it with requested user id. If matches than we delete the document.
BlogPostApiService.destroy(id, _.curry(hasPermission)(req.user))
//hasPermission implementation
function hasPermission(user, blogPost) {
return user && (user.hasRole(UserEnums.roles.admin) || (user._id.toString() == blogPost.author.id.toString()));
}
I implemented FOSOAuthServerBundle in my application to provide an API for mobile application. It seems to work, the user gets the Token and also the RefreshToken but if I make the controller require the user object that always returns null. Also fails the control of the permission, which is only IS_AUTHENTICATED_ANONIMOUSLY.
example:
public function showUserAction(){
$user = $this->getUser()
//$user = null
$auth = $this->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')
//$auth = false
}
How to get the user object in a controller with this type of authentication?
Based on your comment you have created client with different grant_types.
NOTE: If you use grant_type=client_credentials during authentication, there is no User available since you do not specify exact user/password for generating token. In case of grant_type=password you pass username & password and token is linked to user in this case. Hope this makes sense.
Try this:
$user = $this->get('security.token_storage')->getToken()->getUser();