使用 Token 做身份验证
好热闹
流程
登录获取 token
Method and URL Structure
| Method |
Resource URL |
| POST |
/accounts/login/ |
Request Parameters
参数以 application/json 格式,在 request.body 中传递给接口
| Name |
Description |
Required |
Default |
| username |
用户名 |
YES |
|
| password |
密码 |
YES |
|
Request
{ "username":"123456780", "password":"123456",}
cURL Example
$ curl -X POST --data username=123456780&password=123456 http://www.haorenao.cn/account/login/
JSON Response
验证成功返回 token, HTTP Status Code=200; 验证失败返回 detail, HTTP Status Code=400
| Name |
Description |
NOTE |
| token |
User Token |
|
| non_field_errors |
错误信息 |
HTTP Status Code=400 |
{"token":"67bd40249f0016eb03acbbdcef08db6d1ae4e1c8"}
JQeury + CORS 传递 token 到服务器接口
- 为了验证用户身份,token key 要包含在 Authorization HTTP Header 里。
- token key 以 "Token" 做前缀后跟一个“空格”后面跟上 token
Example
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
Javascript Example
$.ajax({ type: 'GET', url: 'http://www.haorenao/api/exmaple/', contentType: 'text/plain', headers: { // 'Token' whith a whitspace Authorization: 'Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }, success: function() { // Here's where you handle a successful response. }, error: function() { // Here's where you handle an error response. }});