简体   繁体   English

如何使用单页应用程序和API后端进行身份验证?

[英]How to do authentication with a single page app and API backend?

I own both, an API backend at api.example.com and a frontend single page app at example.com . 我同时拥有api.example.com的API后端和example.com的前端单页应用程序。 The API is basically a wrapper for a database backend. 该API基本上是数据库后端的包装器。

Now, I want to have a user of the single page app (= client app) to authenticate with the API. 现在,我想让单页应用程序(=客户端应用程序)的用户通过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. 为此,据我所知,客户端(=单页应用程序)将client_id和user_id一起发送到API,然后API发出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. 我正在寻找一个简单的参考或一个好的概念来让登录的用户访问API应用程序。

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 (eg POST /api/v1/auth/new), 客户端应用向您的API发出请求以获取未经授权的令牌(例如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 (eg POST /api/v1/mobile_authenticate), 客户端应用将令牌以及登录名,密码和请求签名发送到API(例如POST / api / v1 / mobile_authenticate),
  5. The API validates and verifies the credentials, API会验证和验证凭据,
  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? 如何简化或改善呢?

I'm using the api key for the permission check in the server API. 我在服务器API中使用api密钥进行权限检查。 The workflow how the api key works is as below. api键的工作流程如下。

  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 (eg POST /api/v1/users/validate). 客户端应用向API请求以获取api密钥(例如POST / api / v1 / users / validate)。
  3. The client app accesses the API with the api key. 客户端应用程序使用api密钥访问API。 (If it is the http request, the api key can be included in the http header or query string.) (如果是http请求,则api键可以包含在http标头或查询字符串中。)

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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