简体   繁体   中英

Ionic + AngularJs + Token based authentication

I've set up a standard Ionic Framework (with ionic start myapp tabs ), and I've got a Laravel PHP backend on the other side (which has the database and so on).

Now what I want is to ask the database of my backend from my mobile-app (it'll be a native app, compiled by PhoneGap). There's problems with CORS to be solved, it seems, and I've read a lot of approaches on how to do it, but none really worked.

What is a good way to authenticate (token-based) to my external backend server, and then, once authenticated ask the server API for various things? Does anyone additionally have a good tutorial and/or working example?

This is the tutorial may help you how to use token system with angular and node js.Coming to data base you can use mysql.When using token based authentication header should have a valid token on every end point to server.you can your feasible token generators also lik oauth2.

http://code.tutsplus.com/tutorials/token-based-authentication-with-angularjs-nodejs--cms-22543

To solve CORS problem add this php code to the head of your php api

if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 166400'); 
}

I don't know whether this response can do something good right now. But to be precise, CORS can be avoid by following below steps.

First create a separate php file in your server and named it as "api.php" (or whatever you prefer) and include this.

   <?php
       if (isset($_SERVER['HTTP_ORIGIN'])) {
           header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
           header('Access-Control-Allow-Credentials: true');
           header('Access-Control-Max-Age: 86400');    // cache for 1 day
       }

       // Access-Control headers are received during OPTIONS requests
       if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

           if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
                header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         

           if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
                header("Access-Control-Allow-Headers:        {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

           exit(0);
       }
   ?>

Then in you other php files which send responses to the client use

   include_once './api.php'; // or the name use above

That will do the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM