Cookie 和Token

129 阅读1分钟

1、cookie介绍

  1. 网站利用cookie记住用户以便下次登陆时候不用重新输入用户名和密码
  2. cookie鉴权介绍:无状态协议使用cookie辨别客户端

A cookie authentication is a link between the client and the server. Using the stateless HTTP protocol, it uses HTTP cookies to authenticate client requests and preserve session data on the server.

  1. 客户端收到服务端发来的cookie,存储在localStorage中,下次请求服务器会带上cookie。

In this approach, the client receives a cookie from the server, which is then saved in the browser's local storage. To confirm that requests belong to the same user and maintain user authentication, the client's browser will send that cookie along with each request in future interactions with the server.

2、cookie鉴权的工作原理

  1. 用户首次登陆网站,向服务端发送登陆请求
  2. 服务端验证通过则创建一个session存放在数据库中
  3. 服务端会返回一个cookie,放在Set-Cookie字段中返回给客户端
  4. 客户端下次请求会带上cookie,服务端和服务器存储的cookie比较,判断用户合法性
  5. 客户端登出app后,本次会话的所有session和cookie都会被删除

JWT

Json web Token 跨域解决方案

1、为什么会有JWT

  1. 传统的session鉴权不易扩展,如果是分布式服务器,则每台服务器都要共享cookie
  2. JWT可以是服务器不保存session,变成无状态的

1、JWT的三个部分

  1. 头部
  2. 负载
  3. 签名

2、使用方式

  1. 将token本地存储,下次请求带上
  2. 在http请求头 Authorization:

3、一般存储在哪里

1、取决于token类型的应用要求 2、存储在localstorage容易引发xss-跨站点脚本攻击