Login/Authentication with Angularjs and PHP

Asked

Viewed 2,741 times

6

Well, I’m making one WebApp where I have a login page before accessing the app and within the app I have some restricted areas.
The Webapp is running everything right, but I ended up getting stuck at the time of processing the login and authentication.

The Webapp is based on AngularJs and PHP with database in MYSQL.

What do I have:

For now I am using a simple login with authentication through PHP. I can log in and display the Webapp only if you are logged in. Ok. But I can’t go any further than that. A brief example of the code I’m using:

index php.

<?php session_start();
    include ('dist/php/config.php');

    if(isset($_GET['out'])){
        session_destroy();
        back("#");
    }
    if((!empty($_POST['user'])) && (!empty($_POST['password']))){

        $p = ['user'=>$_POST['user'], 'password'=>$_POST['password']];
        $r = sql("select * from users where user= :user and password = :password",$p);
        if($r != 0){
            foreach($r as $ln){
                $_SESSION['loggedin']=$ln['name_user'];
            }
        } else {
            $msg = "<div class='login_fb'><p>User or password incorrect</p></div>";
        }
    }

    if(!empty($_SESSION['loggedin'])){
        include "system.php";
    } else { ?>

<head>
    <meta charset="UTF-8" />
    [... resto do head ...]
</head>
<body>
     [... resto do body com form de login ...]
</body>
<?php } ?>

The route system I use in the app is the ui-router.

The problem I have faced for now is in authenticating the user and keeping this data for future use. Data such as user name, id and category of permission it is entered. Even keep this data even after a refresh of the page.

My goal

What I want is this:

  • Log in to WebApp;
  • Keep user data (as said before) for future use on other pages and in the various actions that the user can do;
  • Be possible to refresh the page or close the tab and return later without losing login (nor user data);
  • Control user access. Ex.: release page X only if the user is in the "Super Admin";
  • Make access impossible without going through the form. Ex.: Unable to access the page by typing directly in the URL - Return with message "You do not have permission" or "You need to be logged in".;

I even found some examples and tutorials on the internet, but they are either too complex, or have no clear documentation to follow, or even in some cases have some very harmful flaws. The best content I could it was this one but the explanation already begins at a more advanced point. I needed more of a guide in the initial steps.

For example, how to validate login based on form data and then keep it cached/cookis (would that be?) and then proceed with some areas described in the link tab above.

I also found a reference recommending the use of $cookie ($cookieStore has become obsolete, according to the Cdocs) thus:

app.run(['loginService', function(loginService){
    var username = $cookieStore.get('username');
    var password = $cookieStore.get('password');
    loginService.login(username, password);
}]);

But is it correct/advisable to use it this way? Because we would be manipulating the variable of the password within the angular, it can not bring risks to the security of the user login? As far as I know, it’s not ideal.

What I need to know:

  • Is this login template (through that php code) I’m using the recommended one? Is there any better or more suitable for my purpose?
  • How can I prevent the user from accessing a WebApp without having gone through the login process? (I believe it will be automatically answered if I manage to log in with the data cache for use in future sessions).
  • How can I store this customer data (as well as login) so that when it returns to the page, stay logged in??
  • This data needs to be maintained in all page change/output scenarios, as long as there is no output through 'Logout''.

Finally, that’s it. I believe that with the information to make the initial Handle I can get a north to give procedure to the Webapp.

1 answer

3

I suggest you study more about data-driven applications. You don’t have to worry about route security at the frontend because it does not exist.

Angularjs is an excellent tool to create Single Page Applications, that is, you do not need to generate new GET requests directly from the browser and mixing PHP with HTML/Javascript.

Start from the basics and try to evolve little by little.

  • Write an HTML with login form
  • Write a controller for this HTML that makes an Ajax request and receives a 200 OK response in case of successful authentication or 4xx error in case of authentication failure.
  • Try moving controller request logic to a service / Factory in Angular.
  • Write a function that requests the server to verify that there is a valid authentication (session or token). This way, every time the user loads the application for the first time, you can check if there is a logged-in user.
  • Store basic user data logged in (name, email) in $cookies or $ngStorage.
  • Write your first page Hello World, {{usuário}} for the logged in user.

After reaching these steps, you may notice that you can access the Hello World page even when you are not authenticated, but this is a matter of usability and not security. The security must be contained in your server (backend application) because frontend security is easily breakable. That is, worry first about reaching the basic safe (even if the frontend presents you hello world without authenticating), but do not show the user name without authenticating (secure). In a second moment you will be able to study how to ensure the safety of routes in Angularjs. This will not bring security to your app, but better usability for users who are not malicious.


Want a practical example of what I’m talking about? Go to https://conta.nubank.com.br/ and after loading the page, delete the #login of the url and type #transactions (the URL will look like this: https://conta.nubank.com.br/#/transactions). Note that you have full access to the frontend application even without being authenticated, however there is no information in this application. The data of all customers are secure and the frontend security is more a matter of usability than actually security.

  • Today I have already managed to develop a module that is working very well for my case. Also, I can block access to areas that the user should not/cannot access. For that, I migrated to the ui-router which has the function of resolve who might make a request to my service and verify (with a cookie) if the user is authenticated and release or not the access. But I literally did all the steps you described. If anyone else has that question, surely your answer is great.

  • Celsomtrindade, I am going through the same as you and with a very short time. Is there any way you can provide the solution found? Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.