免登陆,什么是免登陆?实现的是什么?
首先登陆你的微应用需要账号密码,免登陆就是通过钉钉点击你的微应用进入不需要输入账号密码。
所以实现免登陆的目的就是要获取通过微应用点击进入的用户的钉钉用户信息,然后把这个用户信息和你数据库里面的用户相关联,比如手机号相同对比手机号,或者保存钉钉userid到你的数据库,下次对比
1.先根据appid获取code。钉钉会把code加在你的回调地址后面
//首页地址是:******/goMobileLogin?appid=dinged340df3eb1274d2
@RequestMapping(value = "/goMobileLogin", method = RequestMethod.GET)
public ModelAndView goMobileLogin(HttpServletRequest request,
HttpServletResponse response) throws IOException {
if (StringUtils.isNotBlank(request.getParameter("appid"))) {//钉钉登录返回ding.jsp,把appid传过去
ModelAndView mod = new ModelAndView();
mod.addObject("appid", request.getParameter("appid"));
mod.setViewName("/login/ding");
return mod;
ding页面访问地址:
<meta http-equiv="refresh" content="0;URL=https://oapi.dingtalk.com/connect/oauth2/authorize?appid=<%=request.getParameter("appid")%>&response_type=code&scope=SCOPE&redirect_uri=http;//xxxx.com/login/goDingLogin(你的项目回调地址)&state=STATE"/>
2.你回调地址获取链接传过来的code
@RequestMapping(value = "/goDingLogin", method = RequestMethod.GET)
public ModelAndView goDingLogin(HttpServletRequest request,
HttpServletResponse response) throws IOException {
if (StringUtils.isNotBlank(request.getParameter("code"))) {//获取code
String code = request.getParameter("code");
3.获取了code后,根据code和access_token来获取钉钉用户的个人信息,用下面的方法获取token
String token=getToken();//获取token
//获取用户信息
HttpClient httpClient=new DefaultHttpClient();
URI url = new URI("https://oapi.dingtalk.com/user/getuserinfo?access_token=token&code=code ");
HttpGet get = new HttpGet(url);
HttpResponse response = httpClient.execute(get);
HttpEntity entity=response.getEntity();
if(entity!= null){
JSONObject jsonObject=JSONObject.parseObject(EntityUtils.toString(entity));
if(null!=jsonObject.get("userid")){
system.out.print(jsonObject.get("userid"))//获取钉钉用户的id
}
}
获取token的方法
public static String getToken() throws ClientProtocolException, IOException{
HttpClient httpClient=new DefaultHttpClient();
URI url = new URI("https://oapi.dingtalk.com/gettoken?corpid=dinged340df3eb1274d2&corpsecret=WPxxxInU-CUXXQ");
HttpGet get = new HttpGet(url);
HttpResponse response = httpClient.execute(get);
HttpEntity entity=response.getEntity();
if(entity!= null){
JSONObject jsonObject=JSONObject.parseObject(EntityUtils.toString(entity));
if(jsonObject.get("errcode")==0){
return jsonObject.get("access_token").toString();
}
}
}
//如果报错javax.net.ssl.SSLException: hostname in certificate didn't match: <oapi.dingtalk.com> != <*.laiwang.com> OR <*.laiwang.com>
//需修改了HOST验证,此处省略,交流495120021
两个工具类:
-------------------------
-------------------------
-------------------------
-------------------------
-------------------------
-------------------------
-------------------------
-------------------------
-------------------------
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。