中文版在英文版之后。
HTTP Authentication
AAAis the abbreviation forAuthentication,AuthorizationandAccounting, in other words, validating you are exactly you, validating you have permission to operate over specific resources and charging you on your operations over those resources.
POST /users/login
GET /users/:uid/invoices
POST /users/:uid/invoices/:id/payments
Consider our business logics: login, fetch invoices and invoke invoice payment.
Due to HTTP’s statelessness, when GET /users/:uid/invoices and POST /users/:uid/invoices/:id/payments received, Server needs to figure out the caller is exactly the one calling POST /users/login. Currently there are two common solutions.
First solution: session
- Client calls
POST /users/login - Server creates a
sessionand sendssession_idandexpiration timeback to Client inSet-Cookieheader ofHTTP Response - Client calls API with
session_idinCookieheader - Server looks in session pool for a
sessionwithsession_idto validate user’s identity
session on Server has expiration time and will be destroyed after expired.
Second solution: token
- Client calls
POST /users/login - Server issues a pair of encrypted
access token(including user information andexpiration time) andrefresh token, and sends back to Client inbodyofHTTP Response - Client calls API with
access tokeninAuthorizationheader - Server decrypts
access tokenand extracts user information to validate user’s identity
access token has expiration time, and it cannot be used for authentication and calling API after expired. However, Client can call POST /token/refresh with refresh token to apply for a new pair of access token and refresh token.
HTTP 鉴权
AAA是Authentication、Authorization、Accounting的缩写,通俗的说就是,验证你是你,验证你有权限对某个资源进行操作,对你操作资源的行为进行计费。
POST /users/login
GET /users/:uid/invoices
POST /users/:uid/invoices/:id/payments
考虑我们的业务逻辑:登陆,获取账单,唤起支付。
由于 HTTP 无状态,在调用 GET /users/:uid/invoices 和 POST /users/:uid/invoices/:id/payments 的时候,服务器需要确认,调用方是之前调用 POST /users/login。目前有两种常见的做法。
第一种:session
- 客户端调用
POST /users/login - 服务端创建一个
session并得到一个session_id和expiration time,在HTTP Response的Set-Cookie头里返回给客户端 - 客户端后续调用 API 时,在
Cookie头里带上session_id - 服务端会进行查询验证
session_id的session是否存在,从而确认客户端的身份
服务端的 session 有 expiration time,过期之后自动销毁。
第二种: token
- 客户端调用
POST /users/login - 服务端颁发一对包含用户信息的加密过的
access token(包含expiration time) 和refresh token,在HTTP Response的body里返回给客户端 - 客户端后续调用 API 时,在
Authorization头里带上access token - 服务端解密
access token得到用户信息,从而确认客户端的身份
access token 本身具有 expiration time,过期之后,access token 不再具有验证身份的功能,也就无法继续调用其他 API,此时可以通过 POST /token/refresh 带上 refresh token 向服务端申请重新颁发一对 access token 和 access token。