How to do authentication with a single page app an

2019-03-17 07:26发布

问题:

I own both, an API backend at api.example.com and a frontend single page app at example.com . The API is basically a wrapper for a database backend.

Now, I want to have a user of the single page app (= client app) to authenticate with the API. For this, as far as I understand, the client (= single page app) sends a client_id together with a user_id to the API, and the API then gives out an AccessToken.

However, in my single page app, I am not sure where/how to store the access token. I am looking for a simple reference, or a good concept to have a logged in user access the API application.

A friend suggested me this flow:

  1. The client displays inputs for login (be it e-mail or username) and password,
  2. The client app makes a request to your API to obtain an unauthorized token (e.g. POST /api/v1/auth/new),
  3. The server creates a token for the app and sends it back,
  4. The client app sends the token along with the login, password and request signature to the API (e.g. POST /api/v1/mobile_authenticate),
  5. The API validates and verifies the credentials,
  6. If everything is OK the app uses the token to make further on the user's behalf.

Any thoughts? How can this be simplified or improved?

回答1:

I'm using the api key for the permission check in the server API. The workflow how the api key works is as below.

  1. The client app displays inputs for login (be it e-mail or username) and password.
  2. The client app makes a request to the API to obtain an api key (e.g. POST /api/v1/users/validate).
  3. The client app accesses the API with the api key. (If it is the http request, the api key can be included in the http header or query string.)

Hope it helps.