web接入微博第三方登录

时间:2022-01-25 21:29:38

微博第三方登录

最近刚好在学习第三方登录,这里先做一下微博第三方登录的记录,因为qq第三方登录必须要完成网站备案后才能进行,后面再进行补充。

大致可以分成下面几个步骤

web接入微博第三方登录

下面根据我自己的实现过程做一下总结吧。

  1. 准备工作
    (1)首先需要有一个准备接入第三方登录的引用,这里可以是自己的一个小案例web项目。
    (2)需要准备一个域名,并判定自己的应用,这样通过微博审核才能获取到app key和secret
域名申请对于只是想要学习第三方登录开发过程的同学来说是比较麻烦的,首先大家需要去一些云服务器上面租一个服务器,再上面部署自己的应用,这里可以选择的云还是很多的,然后再买一个域名,并解析服务器ip。
  1. 申请appkey
    准备工作完成后,我们就需要到微博开放平台上进行申请了。
    http://open.weibo.com/

    web接入微博第三方登录

    完成开发者的身份认证后,我们就需要创建一个应用,然后提交审核,这里需要用到之前绑定的域名等信息,审核通过后就可以获得app key和app secret。
    web接入微博第三方登录

这样子 微博审核通过后,我们可以获得开发中需要用到的东西了,然后就可以进行下面的开发。
3. 开发过程
下面我们讲利用微博提供的 java sdk进行第三方登录的开发。
首先下载sdk
https://github.com/sunxiaowei2014/weibo4j-oauth2-beta3.1.1/
下载完成后,我们可以先阅读一个README.md

使用方法

1、 请先填写相关配置:在Config.properties里 client_ID :appkey 创建应用获取到的appkey client_SERCRET :app_secret 创建应用获取到的appsecret redirect_URI : 回调地址 OAuth2的回调地址

2、 然后调用example里:OAuth4Code.java

public class OAuth4Code {

public static void main(String [] args) throws WeiboException, IOException{
    Oauth oauth = new Oauth();
    BareBonesBrowserLaunch.openURL(oauth.authorize("code"));
    System.out.print("Hit enter when it's done.[Enter]:");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    String code = br.readLine();
    Log.logInfo("code: " + code);
    try{
        System.out.println(oauth.getAccessTokenByCode(code));
    } catch (WeiboException e) {
        if(401 == e.getStatusCode()){
            Log.logInfo("Unable to get the access token.");
        }else{
            e.printStackTrace();
        }
    }
}
}

3、 运行后会弹出浏览器地址跳转到授权认证页面,然后输入你的微博帐号和密码,会调转到你的回调地址页面,url后面会传递code参数

4、 然后在console输入code就能获取到oauth2的accesstoken

5、 接下来即可调用example,在此以user/show接口为例:

public class ShowUser {

public static void main(String[] args) {
    String access_token = WeiboConfig.getValue("access_token");
    String uid = args[0];
    Users um = new Users(access_token);
    try {
        User user = um.showUserById(uid);
        Log.logInfo(user.toString());
    } catch (WeiboException e) {
        e.printStackTrace();
    }
}
}

access_token为auth4code获取到的oauth2的accesstoken。 由于目前只开放支持code的oauth认证方式,所以sdk暂时只支持code获取token方式。

我们导入示例程序
web接入微博第三方登录

微博第三方登录采用OAuth2.0协议,我们修改/weibo4j-oauth2/src/config.properties配置文件:

client_ID = 你自己的app key
client_SERCRET = 你自已的app sercret
redirect_URI = 回调地址
baseURL=https://api.weibo.com/2/
accessTokenURL=https://api.weibo.com/oauth2/access_token
authorizeURL=https://api.weibo.com/oauth2/authorize
rmURL=https://rm.api.weibo.com/2/

关于回调地址,就是微博认证成功后返回的页面,这个页面应该是开发者自己开发的页面,这个页面可以用来获取微博登录用户的信息等。这里需要在微博开放平台->我的应用->应用信息->高级信息->OAuth2.0 授权设置中进行配置,如果这个地址和配置文件不一致会出现授权页面出错的问题。
打开/weibo4j-oauth2/examples/weibo4j/examples/oauth2/OAuth4Code.java
运行成功后就可以看到第三方登录的信息。

sample演示成功后,我们可以把第三方登录引入自己的项目中了

package lab.io.rush.controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import weibo4j.Oauth;
import weibo4j.examples.oauth2.Log;
import weibo4j.model.WeiboException;
import weibo4j.util.BareBonesBrowserLaunch;

@Component
@RequestMapping("/weibologin.do")
public class weiboLoginController {

    @RequestMapping
    public ModelAndView handleRequest(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        Oauth oauth = new Oauth();
        String url = oauth.authorize("code",null);
        response.sendRedirect(url);
//      BareBonesBrowserLaunch.openURL(oauth.authorize("code",null));
        return null;
    }

}

下面是回调地址的代码:

package lab.io.rush.controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import weibo4j.Oauth;
import weibo4j.Users;
import weibo4j.examples.oauth2.Log;
import weibo4j.model.User;
import weibo4j.model.WeiboException;
import weibo4j.util.BareBonesBrowserLaunch;

@Component
@RequestMapping("/auth.do")
public class authController {
    @RequestMapping
    public ModelAndView handleRequest(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        String code = request.getParameter("code"); 
            Oauth oauth = new Oauth(); 
            String token;
            try {
                token = oauth.getAccessTokenByCode(code).toString();
                String str[] = token.split(","); 
                String accessToken = str[0].split("=")[1]; 
                String str1[] = str[3].split("]"); 
                String uid = str1[0].split("=")[1]; 
                Users users = new Users() ; 
                users.client.setToken(accessToken) ;
                User weiboUser = users.showUserById(uid);
                String name = weiboUser.getScreenName();
                request.getSession().setAttribute("user", name); 
            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }       
        response.sendRedirect(request.getContextPath()+"/index.do");
        return null; 
    }
}

这里需要添加jar包的支持,相应的依赖项如下:

<!-- https://mvnrepository.com/artifact/com.belerweb/weibo4j-oauth2 -->
    <dependency>
        <groupId>com.belerweb</groupId>
        <artifactId>weibo4j-oauth2</artifactId>
        <version>2.1.1-beta2-3</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
    <dependency>
        <groupId>commons-httpclient</groupId>
        <artifactId>commons-httpclient</artifactId>
        <version>3.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
    <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        <version>1.10</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.6.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/log4j/log4j -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.9</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.1.2</version>
    </dependency>

这样子微博的第三方登录就可以成功接入自己的应用了。