Nail JSAPI front-end authentication

Source: Internet
Author: User
Tags ticket

Nails two times development is divided into the following table shows three types of development, only enterprise internal application needs to JSAPI authentication.

Type

Development method

JSAPI Authentication

Application Scenarios

Third-party enterprise applications

E Application Development

Don't need

Used for post to nail application market for download by users, application optional fee or free, need to collect margin and apply audit

Enterprise Internal application

H5 Development, also began to support E - application development in the middle of 8 months

Need

Can only be applied within the enterprise, cannot be posted to nail market

Third party personal applications

E Application Development

Need

Applications are not linked to the enterprise and serve the individual

Let's take a look at the JSAPI authentication process, which is divided into four steps:

    1. Get token
    2. Get ticket
    3. Get a digital signature
    4. Set permissions

View Nail Development documentation, it gives two JSAPI authentication demo, Java and PHP, respectively, need front and back, and this article is about the pure front-end JSAPI authentication, fully realize the separation of front and rear.

The following code will use the three JS dependency packages:

Import Cryptojs from ' Crypto-js '; Encryption, used to generate a  digital signature * as DD from "dingtalk-jsapi" "Axios"; HTTP request

Hint: The following code, with ES6 and ES7 some syntax, no contact with friends, can self-Baidu

1. Get token

First, the token is obtained from the nail server based on the corpid and Corpsecret parameters.

/** * *function  getToken (    params) {return await Axios.get ('/proxy/gettoken ', {            params        })        . Then (function(response) {             return  response.data.access_token;        });

Attentive friends will find that the URL of the Axios request does not directly specify the Oapi.dingtalk.com/gettoken, this is because directly write this URL, there will be cross-domain problems, so, here we use the proxy.

Proxy can use the Nginx Proxy or node agent, which is recommended here with node Proxy.

Because the request for Proxy is HTTPS request, I did not run through the Nginx proxy HTTPS request, if there is a friend ran through the Nginx agent, trouble to tell a sound, also learn the following.

2, set up the agent

If you create a project with VUE-CLI, you can configure it directly in the proxytable as follows:

proxytable: {     '/proxy ': {        ' oapi.dingtalk.com ',        false,         //  set cross-domain        true,        pathrewrite:          {' ^/proxy ': '        }     }  }

However, the above configuration can only be used in the dev development environment, if you need to use it in a production environment, or you need to write your own Nodejs code implementation, as follows:

var express = require (' Express '); var proxy = require (' Http-proxy-middleware '); var app = Express (); App.use ('/proxy ', proxy ({    ' oapi.dingtalk.com ')    , true ,    pathrewrite: {        ' ^/proxy ': '}    }); App.listen (3000);

This amount of code is not very small, any Baidu under the fix.

3. Get ticket

Based on the Access_token obtained above, obtain the ticket from the nail server.

/** * *function  getjsticket (    params) {return await Axios.get ('/proxy/get_jsapi_ticket ', {            params        })        . Then (function(response {            return  response.data.ticket;        });}

4. Get Digital signature

Nail Nail Official Website demo is the background to generate digital signatures, through the CRYPTO-JS front-end encryption library can be ported to the front-end.

The ticket is generated above;

A nonce can be any string;

Timestamp is the current timestamp;

URL is the URL address of the current access, not including # and the following section, pay special attention to this parameter, do not make mistake. If the setting is wrong, you can view the URL address obtained by the Spike server via the dd.error output below.

/** *function  getjsapisingnature (Ticket, nonce, TimeStamp, url    ) {= " Jsapi_ticket= "+ Ticket +" &noncestr= "+ nonce +" &timestamp= "+ timestamp +" &url= "+ URL;     = CRYPTOJS.SHA1 (plaintex). toString ();     return signature;}

5. Set permissions

Setting the required permissions through Dd.config

// Step 4: Set Permissions     dd.config ({        agentid:agentid,        // required, Enterprise ID        //  required, time stamp for signature generation         // required, generate a signed random string        //  required, signature        //  required, List of Jsapi to use, note: Do not bring DD.     });

Jsapilist is a list of permissions, such as:

var jsapilist = [    ' Biz.user.get ',    ' Device.geolocation.get ',    ' Biz.util.uploadImage '];

6. Verification

Once the above configuration is successful, you will be able to invoke the function that requires authentication in Jsapi, as an example of obtaining the current location:

/** * Test code, by invoking the location service, test authentication is correct*/functionTestjsapi () {//Get LocationDd.ready (() ={dd.device.geolocation.get ({targetaccuracy:200, coordinate:1, Withregeocode:false, UseCache:true,//The default is true, if you need to get geographically frequently, set false,Onsuccess:result = {                /*German coordinate result structure {longitude:number, latitude:numb Er, accuracy:number, address:string, province:s Tring, City:string, district:string, Road:strin G, Nettype:string, operatortype:string, errormess                        Age:string, Errorcode:number, Iswifienabled:boolean,                         Isgpsenabled:boolean, Isfrommock:boolean, Provider:wifi|lbs|gps,                    Accuracy:number, Ismobileenabled:boolean} */console.log (Result) alert ("Success:" +json.stringify (Result)}, Onfail:err={console.log (ERR) alert ("Error:" +json.stringify (err))}    });    }); //Viewing authentication error messagesDd.error (function(ERR) {alert (' DD Error: ' + json.stringify (ERR)); });}

If authentication fails, the DD.ERROR will output the digital signature parameters used by the nail server, which can be compared with its own parameters.

Attached: string up the Code
AsyncfunctionGetaccesstoken () {//Step 1: Get tokenLet Access_token =await GetToken ({corpid, corpsecret}); //Step 2: Get TicketLet ticket =await Getjsticket ({access_token}); //Step 3: Get a digital signatureLet signature =getjsapisingnature (Ticket, nonce, TimeStamp, URL); //Step 4: Set PermissionsDd.config ({agentid:agentid, corpid:corpid,//required, Enterprise IDTimestamp:timestamp,//required, time stamp for signature generationNoncestr:nonce,//required, generate a random string of signaturesSignature:signature,//Required, SignatureJsapilist:jsapilist//Required , need to use the Jsapi list, note: Do not bring DD.     }); //Test positioning functionTestjsapi ();}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.