springmvc项目里第三方登录(百度,QQ,微信,人人,新浪微博等)

一:第三方登录原理?

  具体的可以去百度一下它的原理。我在这里就把第三方登录简单流程说一下。以上的第三方都是基于auth2.0协议开发的。以百度为例,前提是开发者有一个百度账号,没有可以注册一个,然后去百度开放平台可以选择成为开发者,填写自己详细的资料或公司资料,然后百度进行审核(其他的这一步需要填一个回调地址:作用就是第三方平台能够把值传给你),审核后会给你一个id和key(不同第三方叫法不一样),然后去填写一个合乎规范的回调地址。填写完成后第一步结束。

二:实现例子(我的项目是基于springmvc的,在登录页面放第三方的标识图片,并设置图片超链接)

1.页面登录

<div class="sjh_text1">用以下社交账号直接登录</div>
<div class="sjh_img">
<a href="${renrenAuthUrl}"><img src="../resources/images/renren_r2_c2.png" /></a>
<a href="${baiduAuthUrl}"><img src="../resources/images/baidu.png" /></a>
<a href="${qqAuthUrl}"><img src="../resources/images/qq.png" /></a>
<a href="${xinlangAuthUrl}"><img src="../resources/images/xinliang.png" /></a>
<a href="${weixinAuthUrl}"><img src="../resources/images/weixin.png" /></a>
</div>
</div>

2./**
* 系统页面初始化
*/
@RequestMapping(value="/front_login.htm")
public ModelAndView front_ready(HttpServletRequest request, HttpServletResponse response) {

ModelAndView result=new ModelAndView("/front/front_login");
result.addObject("qqAuthUrl","https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=***&redirect_uri=***&state=test");
result.addObject("baiduAuthUrl", "http://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id=***&redirect_uri=***");
result.addObject("xinlangAuthUrl", "https://api.weibo.com/oauth2/authorize?client_id=***&redirect_uri=***");
result.addObject("weixinAuthUrl", "https://open.weixin.qq.com/connect/qrconnect?appid=***&redirect_uri=***&response_type=code&scope=snsapi_login");
result.addObject("renrenAuthUrl", "https://graph.renren.com/oauth/authorize?client_id=***&redirect_uri=***&response_type=code");
return result;
}

3:/**
* 百度第三方登录
*/
@RequestMapping(value="/baidu_login.htm")
public ModelAndView baidu_login(HttpServletRequest request, HttpServletResponse response) throws IOException {
ModelAndView result=null;
String code=request.getParameter("code");//客户端传回来的授权码
String atokenUrl="https://openapi.baidu.com/oauth/2.0/token?grant_type=authorization_code&code="+code+"&client_id=***&client_secret=***&redirect_uri=***";
String ret =HttpGetUtil.httpGet(atokenUrl);//返回带token的json字符串
com.alibaba.fastjson.JSONObject obj = JSON.parseObject(ret);
String access_token=(String) obj.get("access_token");//取出token
String apiUrl="https://openapi.baidu.com/rest/2.0/passport/users/getInfo?access_token="+access_token;
String uinfoma = HttpGetUtil.httpGet(apiUrl);//返回的用户信息json字符串
if(uinfoma!=null){//授权成功

if(request.getSession().getAttribute("user")==null){//说明是登录页面来的

com.alibaba.fastjson.JSONObject oobj = JSON.parseObject(uinfoma);
String birthday=(String) oobj.get("birthday");
String portrait=(String) oobj.get("portrait");
String userid=(String) oobj.get("userid");
String username=(String) oobj.get("username");
String thirdId="baidu_"+userid;//第三方平台的id
UserInfo userbyRelationId = userInfoService.getByRelationId(thirdId);//判断是账号是否关联过本地账号
if(userbyRelationId==null){//没有关联则注册一个本地账号
UserInfo user=null;
user = userInfoService.getByThirdId(thirdId);
String flag=null;//照片名
if(user !=null){

flag=user.getUserId()+".jpg";
user.setNickname(username);
userInfoService.user_update(user);// 更新姓名(昵称)
user =userInfoService.getUserInfo(user.getUserId());
request.getSession().setAttribute("user", user);
}else{

UserInfo uinfo=new UserInfo();
uinfo.setBirthday(birthday);//生日
uinfo.setNickname(username);//昵称
Date date=new Date();
String time=DateUtil.getDateTimeString(date);
uinfo.setCreateTime(time);//创建日期
uinfo.setStatus(0);//默认初始值为0
uinfo.setThirdId(thirdId);
int userId=userInfoService.insert(uinfo);
if(userId>=0){
StringBuffer sb=new StringBuffer();
sb.append(userId);
String entwoCodeFileName=sb.toString()+".jpg";//二维码图片文件名
String path=request.getContextPath();
String realpath=request.getSession().getServletContext().getRealPath("/");
String an=URLEncoder.encode("&");//&转码
StringBuffer rootUrl=request.getRequestURL();
String tempContextUrl = rootUrl.delete(rootUrl.length() - request.getRequestURI().length(), rootUrl.length()).toString();
String url=tempContextUrl+path+"/userInfo/areward_jump.htm?userId="+userId+"¶m=1";//二维码
String durl=final_param.CNURL+tempContextUrl+path+"/userInfo/areward_jump.htm?userId="+userId+an+"param=0";//短链接
String returl=url;//二维码
String retdurl=EntwocodeUtil.geturl(durl);//短链接
String twocodepath=realpath+File.separator+"upload"+File.separator+"twocode"+File.separator+entwoCodeFileName;//二维码存放的路径
EntwocodeUtil.encodePR(returl,150,150,twocodepath);//生成二维码
uinfo.setLink(retdurl);
uinfo.setQrCode("/upload/twocode/"+entwoCodeFileName);
uinfo.setUserId(userId);
userInfoService.user_update(uinfo);
uinfo =userInfoService.getUserInfo(uinfo.getUserId());
request.getSession().setAttribute("user", uinfo);
flag=userId+".jpg";

}
// 写头像文件
String portraitUrl="http://tb.himg.baidu.com/sys/portrait/item/"+portrait;
byte[] portraitData = BaiduUtil.downloadPortrait(portraitUrl);
String basePath = request.getSession().getServletContext().getRealPath("/");
BaiduUtil.savePortrait(basePath+File.separator+"portrait"+File.separator+flag, portraitData);//图片写入文件夹下,图片名与用户id对应

}
result= new ModelAndView("redirect:/userInfo/front_main.htm");//进入用户主页
}else{//有关联就取出信息

request.getSession().setAttribute("user", userbyRelationId);
result= new ModelAndView("redirect:/userInfo/front_main.htm");//进入用户主页

}
}else{//从绑定页面来的

UserInfo user=(UserInfo) request.getSession().getAttribute("user");
com.alibaba.fastjson.JSONObject oobj = JSON.parseObject(uinfoma);
String userid=(String) oobj.get("userid");
String relationId="baidu_"+userid;//绑定的百度平台的id
UserInfo byrelationId = userInfoService.getByThirdId(relationId);//查询在绑定该账号前,该帐号是否已被注册过
if(byrelationId!=null){

String authErrorName=byrelationId.getNickname();
//String thirdId=byrelationId.getThirdId();
request.getSession().setAttribute("authErrorName", authErrorName);
result=new ModelAndView("redirect:/userInfo/auth_error.htm");//提示该账号已经绑定过了

}else{

user.setRelationId(relationId);
userInfoService.user_update(user);
user=userInfoService.getUserInfo(user.getUserId());
request.getSession().setAttribute("user", user);
request.getSession().setAttribute("relationState", 1);//提示已经绑定成功
result=new ModelAndView("redirect:/userInfo/front_main_3.htm");
}

}

}
return result;
}
4:其他的平台

/**
* QQ第三方登录
*/
@RequestMapping(value="/qq_login.htm")
public ModelAndView qq_login(HttpServletRequest request, HttpServletResponse response) throws IOException {

ModelAndView result=null;
String code=request.getParameter("code");//客户端传回来的授权码
String atokenUrl="https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&code="+code+"&client_id=***&client_secret=*****&redirect_uri=****";
String ret =HttpGetUtil.httpGet(atokenUrl);//返回带token的json字符串
com.alibaba.fastjson.JSONObject obj = JSON.parseObject(ret);
String access_token=(String) obj.get("access_token");//取出token
String openIdUrl="https://graph.qq.com/oauth2.0/me?access_token="+access_token;
String oinfoma = HttpGetUtil.httpGet(openIdUrl);//返回的openId信息json字符串
com.alibaba.fastjson.JSONObject openidobj = JSON.parseObject(oinfoma);
String openId=(String) openidobj.get("openid");//取出openid
String apiUrl="https://graph.qq.com/user/get_user_info?access_token="+access_token+"&oauth_consumer_key=***&openid="+openId;
String uinfoma=HttpGetUtil.httpGet(apiUrl);//返回用户信息的字符串
if(uinfoma!=null){
UserInfo user=null;
com.alibaba.fastjson.JSONObject oobj = JSON.parseObject(uinfoma);
String sex=(String) oobj.get("gender");
String figureurl_qq_1=(String) oobj.get("figureurl_qq_1");
String username=(String) oobj.get("nickname");
String thirdId="qq_"+openId;//第三方平台的id
user = userInfoService.getByThirdId(thirdId);
String flag=null;//照片名
if(user !=null){

flag=user.getUserId()+".jpg";
user.setNickname(username);
userInfoService.user_update(user);// 更新姓名(昵称)
user =userInfoService.getUserInfo(user.getUserId());
request.getSession().setAttribute("user", user);
}else{

UserInfo uinfo=new UserInfo();
uinfo.setNickname(username);//昵称
Date date=new Date();
String time=DateUtil.getDateTimeString(date);
uinfo.setCreateTime(time);//创建日期
uinfo.setStatus(0);//默认初始值为0
uinfo.setThirdId(thirdId);
int userId=userInfoService.insert(uinfo);
if(userId>=0){
StringBuffer sb=new StringBuffer();
sb.append(userId);
String entwoCodeFileName=sb.toString()+".jpg";//二维码图片文件名
String path=request.getContextPath();
String realpath=request.getSession().getServletContext().getRealPath("/");
String an=URLEncoder.encode("&");//&转码
StringBuffer rootUrl=request.getRequestURL();
String tempContextUrl = rootUrl.delete(rootUrl.length() - request.getRequestURI().length(), rootUrl.length()).toString();
String url=tempContextUrl+path+"/userInfo/areward_jump.htm?userId="+userId+"¶m=1";//二维码
String durl=final_param.CNURL+tempContextUrl+path+"/userInfo/areward_jump.htm?userId="+userId+an+"param=0";//短链接
String returl=url;//二维码
String retdurl=EntwocodeUtil.geturl(durl);//短链接
String twocodepath=realpath+File.separator+"upload"+File.separator+"twocode"+File.separator+entwoCodeFileName;//二维码存放的路径
EntwocodeUtil.encodePR(returl,150,150,twocodepath);//生成二维码
uinfo.setLink(retdurl);
uinfo.setQrCode("/upload/twocode/"+entwoCodeFileName);
uinfo.setUserId(userId);
userInfoService.user_update(uinfo);
uinfo =userInfoService.getUserInfo(uinfo.getUserId());
request.getSession().setAttribute("user", uinfo);
flag=userId+".jpg";

}

}
// 写头像文件
byte[] portraitData = BaiduUtil.downloadPortrait(figureurl_qq_1);
String basePath = request.getSession().getServletContext().getRealPath("/");
BaiduUtil.savePortrait(basePath+File.separator+"portrait"+File.separator+flag, portraitData);//图片写入文件夹下,图片名与用户id对应
result= new ModelAndView("redirect:/userInfo/front_main.htm");//进入用户主页
}
return result;

}

/**
* 新浪微博第三方登录
*/
@RequestMapping(value="/xinlang_login.htm")
public ModelAndView xinlang_login(HttpServletRequest request, HttpServletResponse response) throws IOException {
ModelAndView result=null;
String code=request.getParameter("code");//客户端传回来的授权码
String atokenUrl="https://api.weibo.com/oauth2/access_token?grant_type=authorization_code&code="+code+"&client_id=***&client_secret=***&redirect_uri=***";
String ret =HttpGetUtil.httpGet(atokenUrl);//返回带token的json字符串
com.alibaba.fastjson.JSONObject obj = JSON.parseObject(ret);
String access_token=(String) obj.get("access_token");//取出token
String uid=(String) obj.get("uid");//取出uid
String apiUrl="https://api.weibo.com/2/users/show.json?access_token="+access_token+"uid="+uid;
String uinfoma = HttpGetUtil.httpGet(apiUrl);//返回的用户信息json字符串
if(uinfoma!=null){
UserInfo user=null;
com.alibaba.fastjson.JSONObject oobj = JSON.parseObject(uinfoma);
String sex=(String) oobj.get("gender");
String avatar_large=(String) oobj.get("avatar_large");
String username=(String) oobj.get("screen_name");
String thirdId="xinlang_"+uid;//第三方平台的id
user = userInfoService.getByThirdId(thirdId);
String flag=null;//照片名
if(user !=null){

flag=user.getUserId()+".jpg";
user.setNickname(username);
userInfoService.user_update(user);// 更新姓名(昵称)
user =userInfoService.getUserInfo(user.getUserId());
request.getSession().setAttribute("user", user);
}else{

UserInfo uinfo=new UserInfo();
uinfo.setNickname(username);//昵称
Date date=new Date();
String time=DateUtil.getDateTimeString(date);
uinfo.setCreateTime(time);//创建日期
uinfo.setStatus(0);//默认初始值为0
uinfo.setThirdId(thirdId);
int userId=userInfoService.insert(uinfo);
if(userId>=0){
StringBuffer sb=new StringBuffer();
sb.append(userId);
String entwoCodeFileName=sb.toString()+".jpg";//二维码图片文件名
String path=request.getContextPath();
String realpath=request.getSession().getServletContext().getRealPath("/");
String an=URLEncoder.encode("&");//&转码
StringBuffer rootUrl=request.getRequestURL();
String tempContextUrl = rootUrl.delete(rootUrl.length() - request.getRequestURI().length(), rootUrl.length()).toString();
String url=tempContextUrl+path+"/userInfo/areward_jump.htm?userId="+userId+"¶m=1";//二维码
String durl=final_param.CNURL+tempContextUrl+path+"/userInfo/areward_jump.htm?userId="+userId+an+"param=0";//短链接
String returl=url;//二维码
String retdurl=EntwocodeUtil.geturl(durl);//短链接
String twocodepath=realpath+File.separator+"upload"+File.separator+"twocode"+File.separator+entwoCodeFileName;//二维码存放的路径
EntwocodeUtil.encodePR(returl,150,150,twocodepath);//生成二维码
uinfo.setLink(retdurl);
uinfo.setQrCode("/upload/twocode/"+entwoCodeFileName);
uinfo.setUserId(userId);
userInfoService.user_update(uinfo);
uinfo =userInfoService.getUserInfo(uinfo.getUserId());
request.getSession().setAttribute("user", uinfo);
flag=userId+".jpg";

}

}
// 写头像文件
byte[] portraitData = BaiduUtil.downloadPortrait(avatar_large);
String basePath = request.getSession().getServletContext().getRealPath("/");
BaiduUtil.savePortrait(basePath+File.separator+"portrait"+File.separator+flag, portraitData);//图片写入文件夹下,图片名与用户id对应
result= new ModelAndView("redirect:/userInfo/front_main.htm");//进入用户主页
}
return result;
}

/**
* 微信第三方登录
*/
@RequestMapping(value="/weixin_login.htm")
public ModelAndView weixin_login(HttpServletRequest request, HttpServletResponse response) throws IOException {
ModelAndView result=null;
String code=request.getParameter("code");//客户端传回来的授权码
String atokenUrl="https://api.weixin.qq.com/sns/oauth2/access_token?appid=***&secret=***&code="+code+"&grant_type=authorization_code";
String ret =HttpGetUtil.httpGet(atokenUrl);//返回带token的json字符串
com.alibaba.fastjson.JSONObject obj = JSON.parseObject(ret);
String access_token=(String) obj.get("access_token");//取出token
String openId=(String) obj.get("openid");//取出openId
String apiUrl="https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openId;
String uinfoma = HttpGetUtil.httpGet(apiUrl);//返回的用户信息json字符串
if(uinfoma!=null){
UserInfo user=null;
com.alibaba.fastjson.JSONObject oobj = JSON.parseObject(uinfoma);
String sex=(String) oobj.get("sex");
String headimgurl=(String) oobj.get("headimgurl");
String unionid=(String) oobj.get("unionid");
String username=(String) oobj.get("nickname");
String thirdId="wenxin_"+unionid;//第三方平台的id
user = userInfoService.getByThirdId(thirdId);
String flag=null;//照片名
if(user !=null){

flag=user.getUserId()+".jpg";
user.setNickname(username);
userInfoService.user_update(user);// 更新姓名(昵称)
user =userInfoService.getUserInfo(user.getUserId());
request.getSession().setAttribute("user", user);
}else{

UserInfo uinfo=new UserInfo();
uinfo.setNickname(username);//昵称
Date date=new Date();
String time=DateUtil.getDateTimeString(date);
uinfo.setCreateTime(time);//创建日期
uinfo.setStatus(0);//默认初始值为0
uinfo.setThirdId(thirdId);
int userId=userInfoService.insert(uinfo);
if(userId>=0){
StringBuffer sb=new StringBuffer();
sb.append(userId);
String entwoCodeFileName=sb.toString()+".jpg";//二维码图片文件名
String path=request.getContextPath();
String realpath=request.getSession().getServletContext().getRealPath("/");
String an=URLEncoder.encode("&");//&转码
StringBuffer rootUrl=request.getRequestURL();
String tempContextUrl = rootUrl.delete(rootUrl.length() - request.getRequestURI().length(), rootUrl.length()).toString();
String url=tempContextUrl+path+"/userInfo/areward_jump.htm?userId="+userId+"¶m=1";//二维码
String durl=final_param.CNURL+tempContextUrl+path+"/userInfo/areward_jump.htm?userId="+userId+an+"param=0";//短链接
String returl=url;//二维码
String retdurl=EntwocodeUtil.geturl(durl);//短链接
String twocodepath=realpath+File.separator+"upload"+File.separator+"twocode"+File.separator+entwoCodeFileName;//二维码存放的路径
EntwocodeUtil.encodePR(returl,150,150,twocodepath);//生成二维码
uinfo.setLink(retdurl);
uinfo.setQrCode("/upload/twocode/"+entwoCodeFileName);
uinfo.setUserId(userId);
userInfoService.user_update(uinfo);
uinfo =userInfoService.getUserInfo(uinfo.getUserId());
request.getSession().setAttribute("user", uinfo);
flag=userId+".jpg";

}

}
// 写头像文件
byte[] portraitData = BaiduUtil.downloadPortrait(headimgurl);
String basePath = request.getSession().getServletContext().getRealPath("/");
BaiduUtil.savePortrait(basePath+File.separator+"portrait"+File.separator+flag, portraitData);//图片写入文件夹下,图片名与用户id对应
result= new ModelAndView("redirect:/userInfo/front_main.htm");//进入用户主页
}
return result;
}

/**
* 人人网第三方登录
*/
@RequestMapping(value="/renren_login.htm")
public ModelAndView renren_login(HttpServletRequest request, HttpServletResponse response) throws IOException {
ModelAndView result=null;
String code=request.getParameter("code");//客户端传回来的授权码
String atokenUrl="https://graph.renren.com/oauth/token?grant_type=authorization_code&client_id=***&redirect_uri=***&client_secret=***&code="+code;
String ret =HttpGetUtil.httpGet(atokenUrl);//返回带token的json字符串
com.alibaba.fastjson.JSONObject obj = JSON.parseObject(ret);
String access_token=(String) obj.get("access_token");//取出token
String apiUrl="https://api.renren.com/v2/user/login/get?access_token="+access_token;
String uinfoma = HttpGetUtil.httpGet(apiUrl);//返回的用户信息json字符串
if(uinfoma!=null){
UserInfo user=null;
com.alibaba.fastjson.JSONObject oobj = JSON.parseObject(uinfoma);
String avatar= (String) ((JSONArray) oobj.get("avatar")).get(1);
String id=(String) oobj.get("id");
String username=(String) oobj.get("name");
String thirdId="wenxin_"+id;//第三方平台的id
user = userInfoService.getByThirdId(thirdId);
String flag=null;//照片名
if(user !=null){

flag=user.getUserId()+".jpg";
user.setNickname(username);
userInfoService.user_update(user);// 更新姓名(昵称)
user =userInfoService.getUserInfo(user.getUserId());
request.getSession().setAttribute("user", user);
}else{

UserInfo uinfo=new UserInfo();
uinfo.setNickname(username);//昵称
Date date=new Date();
String time=DateUtil.getDateTimeString(date);
uinfo.setCreateTime(time);//创建日期
uinfo.setStatus(0);//默认初始值为0
uinfo.setThirdId(thirdId);
int userId=userInfoService.insert(uinfo);
if(userId>=0){
StringBuffer sb=new StringBuffer();
sb.append(userId);
String entwoCodeFileName=sb.toString()+".jpg";//二维码图片文件名
String path=request.getContextPath();
String realpath=request.getSession().getServletContext().getRealPath("/");
String an=URLEncoder.encode("&");//&转码
StringBuffer rootUrl=request.getRequestURL();
String tempContextUrl = rootUrl.delete(rootUrl.length() - request.getRequestURI().length(), rootUrl.length()).toString();
String url=tempContextUrl+path+"/userInfo/areward_jump.htm?userId="+userId+"¶m=1";//二维码
String durl=final_param.CNURL+tempContextUrl+path+"/userInfo/areward_jump.htm?userId="+userId+an+"param=0";//短链接
String returl=url;//二维码
String retdurl=EntwocodeUtil.geturl(durl);//短链接
String twocodepath=realpath+File.separator+"upload"+File.separator+"twocode"+File.separator+entwoCodeFileName;//二维码存放的路径
EntwocodeUtil.encodePR(returl,150,150,twocodepath);//生成二维码
uinfo.setLink(retdurl);
uinfo.setQrCode("/upload/twocode/"+entwoCodeFileName);
uinfo.setUserId(userId);
userInfoService.user_update(uinfo);
uinfo =userInfoService.getUserInfo(uinfo.getUserId());
request.getSession().setAttribute("user", uinfo);
flag=userId+".jpg";

}

}
// 写头像文件
byte[] portraitData = BaiduUtil.downloadPortrait(avatar);
String basePath = request.getSession().getServletContext().getRealPath("/");
BaiduUtil.savePortrait(basePath+File.separator+"portrait"+File.separator+flag, portraitData);//图片写入文件夹下,图片名与用户id对应
result= new ModelAndView("redirect:/userInfo/front_main.htm");//进入用户主页
}
return result;
}

/**

5:用的工具类

public class HttpGetUtil {

     // 发起http get类型请求获取返回结果
    public static String httpGet(String urlstr) throws IOException {
        URL url = new URL(urlstr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.connect();
        InputStream is = conn.getInputStream();

        byte[] buff = new byte[is.available()];
        is.read(buff);
        String ret = new String(buff, "utf-8");

        is.close();
        conn.disconnect();

        return ret;
    }
}

/**
     * 下载头像图片
     * @author pl
     * @param portrait
     * @return
     */
    public static byte[] downloadPortrait(String portraitUrl) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        try {
            URL url = new URL(portraitUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            InputStream is = conn.getInputStream();

            byte[] buff = new byte[1024];
            int cnt;
            while ((cnt = is.read(buff)) > 0) {
                baos.write(buff, 0, cnt);
            }

            is.close();
            conn.disconnect();

            baos.close();
            return baos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    
    // 写头像文件
    public static void savePortrait(String fileName, byte[] portraitData) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(fileName);
            fos.write(portraitData);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                }
            }
        }
    }

你可能感兴趣的:(spring,mvc,qq,新浪微博,第三方登录,人人)