In fact, the front and back end stipulate some rules to generate the sign signature. When the front end requests the signature to the back end, the signature will always pass. Otherwise, the request will not pass. This way is not absolutely safe, recently just happened to use a simple record

The premise

  • This code applies toVue + axios
  • Need to generate unique identification, reference libraryuuid-js
  • MD5 encryption is required, refer to the libraryjs-md5

Signature Generation process

  1. The front and back ends specify a set of parametersappKeyappSecurity, values can be arbitrarily defined, such asconst appKey = 'appKey'const appSecurity = 'appSecurity'
  2. Intercept each request against the requestedconfigFor processing
    1. Generate timestampconst timestamp = new Date().getTime()
    2. Generate a uniquely identified Nonceconst nonce = UUID.create().toString()
    3. Handle arguments according to convention rules: Receive all arguments in an array of the forma=1, the array format is as follows['a=1', 'b=2', 'params={"demo":1,"test":""}']When a POST request is madeContent-Typeapplication/jsonIs in the format ofparamsFollowed by a string from the request body; Only toContent-Typeapplication/jsonapplication/x-www-form-urlencodedThe request body data of the request is signed. Other types of request body data are not signed
    4. The parameter array is deduplicatedappKey,timestamp,nonceParameter adds to the parameter array
    5. Sort an array of parameters, from smallest to largest by the first ASCII letter of each entry
    6. Concatenate each item in the parameter array into a string, removing all=“, and add at the endappSecurityThe value of the
    7. MD5 encryption is performed on the generated string, which is processed into a 32-bit encrypted string in all uppercase. This is sign
    8. willappKey,timestamp,nonce,signAdd the request header

Reference code

  • Request encapsulation, request interceptionhttp.js
import axios from 'axios'
import { createSign } from '... /sign.js'

axios.interceptors.request.use((config) = > {
    if (config.method === 'post' && config.headers['Content-Type'= = ='application/x-www-form-urlencoded') {
        letdata = qs.parse(config.data) config.data = qs.stringify({ ... data }) } config.params = { ... config.params,// ...
    }
    config = createSign(config)
    return config;
}, (error) = > {
    return Promise.reject(error.toString());
})
Copy the code
  • Encapsulate the logic that generates the signaturesign.js
import UUID from 'uuid-js'
import md5 from 'js-md5'

/ / signature
const appKey = 'appKey'
const appSecurity = 'appSecurity'

// config is the config of the block request
export const createSign = (config) = > {
    const timestamp = new Date().getTime()
    const nonce = UUID.create().toString()

    let params = [].concat(handleUrl(config.url), handleParams(config.params), handleData(config))
    // repeat items
    params = ['appKey=' + appKey, 'timestamp=' + timestamp, 'nonce='+ nonce, ... newSet(params)]
    // Sort by the first letter
    params = params.sort((a, b) = > {
        return (a + ' ').localeCompare(b + ' ')})// Assemble a string
    params = params.join(' ').replace(/\=/g.' ') + appSecurity
    // console.log(params)
    / / the md5 encryption
    let sign = md5(params).toUpperCase()
    // Put the argument into contentTypeconfig.headers = { ... config.headers, appKey, timestamp, nonce, sign }return config
}

// Parse the parameters after the Url
function handleUrl(url){
    let index = url.indexOf('? ')
    if(index ! = = -1) {let str = url.substring(index + 1)
        return str.split('&').filter(item= > {
            return item.split('=') [1]})}else{
        return[]}}// Parse params objects
function handleParams(params){
    if(Object.keys(params).length ! = =0) {let res = []
        for (const key in params) {
            if (params[key]) {
                res.push(key + '=' + params[key])
            }
        }
        return res
    }else{
        return[]}}// Parse the data object
function handleData(config){
    const data = config.data
    const contentType = config.headers['Content-Type']
    let res = []
    if(config.method ! = ='get') {if(contentType === 'application/x-www-form-urlencoded'){
            res = data.split('&').filter(item= > {
                return item.split('=') [1]})}if(contentType === 'application/json'){
            res.push('params=' + JSON.stringify(data))
        }
    }
    return res
}
Copy the code

Conclusion word

Still, the front end of things are not absolutely safe, can only be strengthened by a variety of means, sign signature this way is a more common means, remember the convenience of development.