ionic4 钉钉H5微应用免登录

ionic4 钉钉H5微应用免登录

【实现结果】
钉钉内打开企业嵌入发布后的H5微应用无需在输入账户密码!
【需要参数】
企业H5微应用发布后的APPID、AppSecret
【实现过程】
前端界面代码实现

安装命令
npm install dingtalk-jsapi --save
引入
import * as dd from 'dingtalk-jsapi';
index.html
 

核心:
isDing() {
    if (dd.env.platform !== 'notInDingTalk') {
      // 进行钉钉登录操作
      dd.ready(() => {
        dd.runtime.permission.requestAuthCode({
          corpId: DingTalkEnum._corpId,
        }).then((onSuccess) => {
          //  获取临时授权码(code )
          this.code = onSuccess.code;
          const url = '请求接口' + this.code ;
          this.http.get(url).subscribe(
              res => {
                if (res.json().code === '0000') {
                  this.token = res.json().data[0].token;
                  this.name = res.json().data[0].userCode;
                  // alert(this.token);
                  localStorage.setItem('Authorization', this.token);
                  localStorage.setItem('userCode', this.name);
                  this.loadUserPage();
                } else {
                  localStorage.removeItem('Authorization');
                  localStorage.removeItem('userCode');
                  this.loadUserPage();
                }
              }
          );
// 成功即相当于 onSuccess
        }, (onFail) => {
          // 失败即相当于 onFail
          this.error = onFail.error;
        });
      });
    } else {
      this.display = true;
    }
  }

后端核心代码

package com.tfjybj.english.provider.controller;
@Api(tags = {"钉钉免登录接口"})
@RequestMapping(value = "/DingTalkLoginController")
@RestController
public class DingTalkLoginController {
    @Value("${ding_corpid}")
    private String corpid;
    @Value("${ding_corpsecret}")
    private String corpsecret;

    /**
     * 钉钉免密登录
     * @param code 钉钉临时授权码
     * @return access_token 钉钉Token
     */
    @ApiOperation("获取钉钉token")
    @GetMapping(value = "/loginByCode/{code}")
    public AllUserModel getDingToken(@ApiParam(value = "免密登录临时授权码", required = true) @PathVariable String code) {
        // 由AppKey与AppSceret组合临时请求参数
        String param = "corpid=" + corpid + "&corpsecret=" + corpsecret;
        // 请求获取AccessToken
        String accessToken = HTTPUtils.sendGet(DingTalkEnumUntil.DING_TALK_ENUM_UNTIL_GETTOKEN.getMessage(), param);
        // 将返回数据实体接收
        AccessTokenModel accessTokenModel = JSON.parseObject(accessToken, AccessTokenModel.class);
        // 取出AccessToken
        String access_token = accessTokenModel.getAccess_token();
        // 根据token和临时code获取userid
        String dingId = this.getUserInfo(access_token, code);
        // 返回根据钉钉ID登录获取的数据
        return this.dingIdLogin(dingId);
    }


    /**
     * 查询钉钉取出userID
     * @param access_token  钉钉Token
     * @param code 临时Code
     * @return
     */
    public String getUserInfo(String access_token, String code) {
        String param = "access_token=" + access_token + "&code=" + code;
        String userInfo = HTTPUtils.sendGet(DingTalkEnumUntil.DING_TALK_ENUM_UNTIL_GETUSERINFO.getMessage(), param);
        UserDingModel userDingModel = JSON.parseObject(userInfo, UserDingModel.class);
        //返回ding_Id
        return userDingModel.getUserid();
    }


    /**
     *请求当前权限钉钉免密登录接口
     * @param dingId 钉钉企业唯一UserID
     * @return 当前企业内用户信息
     */
    private AllUserModel dingIdLogin(String dingId) {
        String userDing = sendGet(DingTalkEnumUntil.DING_TALK_ENUM_UNTIL.getMessage(), dingId);
        return JSON.parseObject(userDing, AllUserModel.class);
    }


    /**
     *
     * @param url
     * @param param
     * @return
     */
    public static String sendGet(String url, String param) {
        return sendGet(url, param, false);
    }

    /**
     *
     * @param url
     * @param param
     * @param isJson
     * @return
     */
    public static String sendGet(String url, String param, Boolean isJson) {
        String result = "";
        BufferedReader in = null;

        try {
            String urlNameString = url +  param;
            URL realUrl = new URL(urlNameString);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            if (isJson) {
                connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            }

            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.connect();
            Map> map = connection.getHeaderFields();
            Iterator var9 = map.keySet().iterator();

            while(var9.hasNext()) {
                String key = (String)var9.next();
                System.out.println(key + "--->" + map.get(key));
            }

            String line;
            for(in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")); (line = in.readLine()) != null; result = result + line) {
            }
        } catch (Exception var19) {
            result = "发送 POST 请求出现异常!";
            var19.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception var18) {
                var18.printStackTrace();
            }

        }

        return result;
    }

}

你可能感兴趣的:(--JAVA)