Login credentials

  • Why do I need login credentials
    • HTTP is a stateless protocol
    • After a successful login, the user accesses other data and resources as a user or accesses them via HTTP. The server does not know what it did last step. Must there be a way to prove that we are logged in

cookie

  • Always stored in the client, according to the storage location of the client, cookies can be divided into memory cookies and hard disk cookies
    • The in-memory cookie is maintained by the browser and stored in memory. When the browser closes, the cookie will disappear and its existence time is short
    • Hard disk Cookies are stored on hard disks and have an expiration date. The cookies are deleted only when the user manually deletes them or the expiration date expires
      • No expiration time is set, default is memory cookie closed browser automatically deleted
      • Cookies whose expiration time is not 0 or negative are disk cookies and need to be manually cleared or expire
  • Common properties
    • Effective cycle
      • The default is memory cookie, also known as session cookie, which is automatically deleted when the browser closes
      • Set an expiration time by setting expires or max-age
        • Expires: Sets date.toutcString () to expires= date-in-gmtString-format
        • Max-age: specifies the expiration seconds. Max-age =max-age-in-seconds(for example, 60)6024 * 365)
    • Scope (which urls are allowed to send cookies to)
      • Domain: specifies which hosts can accept cookies
        • If this parameter is not specified, origin is default and does not include subdomain names
        • Specify Domain, including subdomain (for example, Domain=mozilla.org, cookies are also included in the subdomain)
      • What Path under the Path: specify the host can accept cookies (Path = / docs, for example, is the following address matching/docs, / docs/Web, / docs/Web/HTTP)
    Client Setupdocument.cookie = 'name=lp; max-age=5; 'Server Settings (maxAge in milliseconds) ctx.cookies. Set ('name'.'lp', {maxAge:5*1000
    })
    ctx.cookies.get('name')
    Copy the code

session

  • Rely on a cookie

  • Cannot be set on the client side

    Installation of koa - the sessionconst Session = require('koa-session'Create the session configurationconst session = Session({
      key:'sessionid'.maxAge:5*1000.signed:false.// Whether to use an encrypted signature
    },app)
    app.keys=['aaa'] app.use(session) Use ctx.session.user={id,name}Copy the code

Disadvantages of Cookies and sessions

  • Cookies are attached to every HTTP request, increasing traffic invisibly
  • Cookies are transmitted in plaintext, which is a security problem
  • The cookie size limit is 4KB, which is not sufficient for complex requirements
  • For other browser clients (ios\Android), cookies and sessions must be set manually for each request
  • How can distributed systems and server clusters ensure that other systems can correctly resolve shared sessions?
  • The last two are the biggest disadvantages

Token

  • Can be translated as a token
  • After verifying that the user name and password are correct, issue a credential to the user
  • This token acts as a credential for subsequent users to access some interface or resource
  • Use this certificate to determine whether the user has permission to access
  • Therefore, token use is divided into two steps:
    • Token generation: A token is issued during login
    • Verify token: Verifies the token when accessing certain resources or interfaces

JWT – JSON Web Token

  • header
    • Alg: The encryption algorithm is adopted. The default is HMAC SHA256(HS256). The same key is used for encryption and decryption (symmetric encryption).
    • Typ: JWT, fixed value
    • It is encoded using the base64Url algorithm
  • payload
    • The data carried, such as name and ID
    • Default to carry IAT (issued at), token issue time
    • Exp (expiration Time)
    • It is encoded using the base64Url algorithm
  • signature
    • Set up a secretKey and run the HMACSHA256 algorithm by merging the results of the first two
    • HMACSHA256(base64Url(header)+.+base64Url(payload),secretKey)
    • But it is very dangerous if the secretKey is exposed, because the token can then be simulated and decrypted
    / / jsonwebtoken installation
    const jwt = require('jsonwebtoken')
    // Used in the interface
    / / returns a token
    const user = {id:1.name:'lp'}
    const SCRECT_KEY = 'anbfcfakn1345'
    const token = jwt.sign(user,SCRECT_KEY,{ // PRIVATE_KEY
      expiresIn:10.// The unit is seconds
      // algorithm:'RS256',// For asymmetric encryption, specify algorithm
    })
    ctx.body = token
    / / authentication token
    const authorization = ctx.headers.authorization
    const token = authorization.replace('Bearer '.' ')
    try {
      const result = jwt.verify(token,SCRECT_KEY,{// PUBLIC_KEY
        algorithm: ['RS256']
      })
      ctx.body = result
    }catch(error){
      ctx.body = 'Token is invalid'
    }
    
    Copy the code

Asymmetric encryption RS256

  • Private key private key: Used to issue tokens
  • Public key Public key: Used to authenticate the token
  • openssl
    • Generate the private key: genrsa-out private.key 1024
    • Generate a public key: rsa-in private.key -pubout-out public.key
  • Replace SCRECT_KEY