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 to
Vue + axios
- Need to generate unique identification, reference library
uuid-js
- MD5 encryption is required, refer to the library
js-md5
Signature Generation process
- The front and back ends specify a set of parameters
appKey
和appSecurity
, values can be arbitrarily defined, such asconst appKey = 'appKey'
和const appSecurity = 'appSecurity'
- Intercept each request against the requested
config
For processing- Generate timestamp
const timestamp = new Date().getTime()
- Generate a uniquely identified Nonce
const nonce = UUID.create().toString()
- Handle arguments according to convention rules: Receive all arguments in an array of the form
a=1
, the array format is as follows['a=1', 'b=2', 'params={"demo":1,"test":""}']
When a POST request is madeContent-Type
为application/json
Is in the format ofparams
Followed by a string from the request body; Only toContent-Type
为application/json
和application/x-www-form-urlencoded
The request body data of the request is signed. Other types of request body data are not signed - The parameter array is deduplicated
appKey
,timestamp
,nonce
Parameter adds to the parameter array - Sort an array of parameters, from smallest to largest by the first ASCII letter of each entry
- Concatenate each item in the parameter array into a string, removing all
=
“, and add at the endappSecurity
The value of the - MD5 encryption is performed on the generated string, which is processed into a 32-bit encrypted string in all uppercase. This is sign
- will
appKey
,timestamp
,nonce
,sign
Add the request header
- Generate timestamp
Reference code
- Request encapsulation, request interception
http.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 signature
sign.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.