接口自动化——接口鉴权的多种方式

一、后端接口鉴权常用方法

  • cookie
    1. 携带身份信息请求认证
    2. 之后的每次请求都携带cookie信息,cookie记录在请求头中
  • token
    1. 携带身份信息请求认证
    2. 之后的每次请求都携带token认证信息
    3. 可能记录在请求头,可能记录在url参数中
  • auth
    1. 每次请求携带用户的username和password,并对其信息加密
  • oauth2(选修)
    1. 携带身份信息请求认证
    2. 服务端向指定回调地址回传code
    3. 通过code获取token
    4. 之后的请求信息都携带token。

二、cookie 鉴权

  1. cookie 的获取(根据接口文档获取)
  2. 发送携带 cookie 的请求
    • 直接通过 cookies 参数
    • 通过 Session() 对象
class TestWithSession:
    proxy = {"http": "http://127.0.0.1:8888", "https": "https://127.0.0.1:8888"}
    req = requests.Session()

    def setup_class(self):
        url = "http://train-manage.atstudy.com/login"
        data = {"username": "199****9999", "password": "a1***56"}
        resp = self.req.request("post", url, data=data, proxies=self.proxy)
        print(self.req.headers)

    def test_get_userinfo(self):
        url = "http://train-manage.atstudy.com/api/manage/User/Info"
        resp = self.req.request("get", url, proxies=self.proxy)
        print(resp.text)

    def test_manage_tag(self):
        url = "http://train-manage.atstudy.com/api/manage/Tag?type=1"
        resp = self.req.request("get", url, proxies=self.proxy)
        print(resp.text)

三、token 鉴权

  1. token 的获取(根据接口文档获取)
  2. 发送携带 token 的请求(根据接口文档获取)
class TestWithToken:
    proxy = {"http": "http://127.0.0.1:8888", "https": "http://127.0.0.1:8888"}
    headers = {}

    def setup_class(self):
        token = self.login().json()["data"]["token"]
        print(token)
        self.headers["x-litemall-admin-token"] = token

    @classmethod
    def login(cls):
        url = "https://litemall.hogwarts.ceshiren.com/admin/auth/login"
        data = {"username": "hogwarts", "password": "test12345", "code": ""}
        resp = requests.request("post", url, json=data, proxies=cls.proxy, verify=False)
        return resp

    def test_get_dashboard(self):
        url = "https://litemall.hogwarts.ceshiren.com/admin/dashboard"
        resp = requests.request("get", url, headers=self.headers, proxies=self.proxy, verify=False)
        print(resp.text)
        # print(1)

    def test_category_list(self):
        url = "https://litemall.hogwarts.ceshiren.com/admin/category/list"
        resp = requests.request("get", url, headers=self.headers, proxies=self.proxy, verify=False)
        print(resp.text)