微博第三方登陆实现

1 引入基础pom文件

        <dependency>
            <groupId>com.belerweb</groupId>
            <artifactId>weibo4j-oauth2</artifactId>
            <version>2.1.1-beta2-3</version>
        </dependency>
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.3</version>
            <classifier>jdk15</classifier>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.4</version>
        </dependency>

 2 登陆接口实现

    @GetMapping("/wbLogin")
    public void wbLogin(HttpServletResponse response) {
        String backUrl = AuthUtil.REDIRECT_URL;
        String url = AuthUtil.authorizeURL + "?client_id=" + AuthUtil.CLIENTID +
            "&redirect_uri=" + backUrl +
            "&response_type=code";
        System.out.println(url + "---");
        try {
            response.sendRedirect(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

3 回调接口实现

    @RequestMapping("/wbcallBack")
    public DataResult callBack(HttpServletRequest req, HttpServletResponse resp) {
        DataResult dataResult = new DataResult();
        String code = req.getParameter("code");
        try {
            String url = AuthUtil.accessTokenURL + "?client_id=" + AuthUtil.CLIENTID +
                "&client_secret=" + AuthUtil.CLIENTSECRET +
                "&grant_type=authorization_code&code=" + code +
                "&redirect_uri=" + AuthUtil.REDIRECT_URL;
            String s = AuthUtil.doPostString(url);
            System.out.println("==jsonobject==" + s + "==");
            Map map = (Map) JSON.parse(s);
            String accessToken = String.valueOf(map.get("access_token"));
            String uid = String.valueOf(map.get("uid"));
            System.out.println("==accesstoken==uid==" + accessToken + ":" + uid);
            
            AuthUtil users = new AuthUtil();
            users.client.setToken(accessToken);
            
            Person weiboUser = users.showUserById(uid);
            People people = new People();
            people.setId(weiboUser.getId());
            people.setScreenName(weiboUser.getScreenName());
            people.setName(weiboUser.getName());
            people.setProfileImgUrl(weiboUser.getProfileImageUrl());
            people.setAvatarLarge(weiboUser.getAvatarLarge());
            JSONObject jsonObject = JSONObject.fromObject(people);
            System.out.println("==json==" + jsonObject);
            
            String loginByUid = getLoginByUid(uid);
            System.out.println("==loginbyuid==" + loginByUid);
            if (loginByUid != null && !"".equals(loginByUid)) {
                //已经绑定,跳转到首页
                List list = new ArrayList();
                Map<String, Object> map1 = new HashMap<>();
                map1.put("login", loginByUid);
                map1.put("json",jsonObject);
                Map<String, Object> aceessToken1 = AuthUtil.getAceessTokenByUid(uid);
                System.out.println("==accesstoken1==" + aceessToken1);
                list.add(map1);
                list.add(aceessToken1);
                dataResult.setData(list);
                dataResult.setStatus(true);
                resp.sendRedirect("http://www.baidu.com:54523/luaa/api/unLinkInfoWB?username="+loginByUid+"&token="+aceessToken1.get("access_token"));
            } else {
                //未绑定,跳转到绑定并登陆页面
                List list = new ArrayList();
                Map<String, Object> map2 = new HashMap<>();
                map2.put("id", uid);
                list.add(map2);
                dataResult.setData(list);
                dataResult.setStatus(false);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataResult;
    }

4 基础工具类



import cn.com.kjcx.emgw.microservice.uaa.granter.Person;
import net.sf.json.JSONObject;
import org.apache.http.*;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import weibo4j.Weibo;
import weibo4j.http.AccessToken;
import weibo4j.http.HttpClient;
import weibo4j.model.PostParameter;
import weibo4j.model.User;
import weibo4j.model.WeiboException;

import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by  on 2018/9/11
 */
public class AuthUtil extends Weibo {
    public static final String CLIENTID = "3112924562";
    public static final String CLIENTSECRET = "4faa1123451ce268e3fa71bae5eca706";
    public static final String REDIRECT_URL = "http://www.baidu.com:54523/luaa/api/wbcallBack";
    public static final String baseURL = "https://api.weibo.com/2/";
    public static final String accessTokenURL = "https://api.weibo.com/oauth2/access_token";
    public static final String authorizeURL = "https://api.weibo.com/oauth2/authorize";
    public static final String rmURL = "https://rm.api.weibo.com/2/";


    public static AccessToken getAccessTokenByCode(String code) throws WeiboException {
        HttpClient client = new HttpClient();
        return new AccessToken(client.post(
            accessTokenURL,
            new PostParameter[]{
                new PostParameter("client_id", CLIENTID),
                new PostParameter("client_secret", CLIENTSECRET),
                new PostParameter("grant_type", "authorization_code"),
                new PostParameter("code", code),
                new PostParameter("redirect_uri", REDIRECT_URL)}, false));
    }

    public static JSONObject doGetJson(String url) throws IOException {
        JSONObject jsonObject = null;
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String result = EntityUtils.toString(entity, "utf-8");
            jsonObject = JSONObject.fromObject(result);
        }
        httpGet.releaseConnection();
        return jsonObject;
    }

    public static String doPostString(String url) throws IOException {

        DefaultHttpClient client = new DefaultHttpClient();
        
        HttpPost httpPost = new HttpPost(url);
        HttpResponse response = client.execute(httpPost);
        HttpEntity entity = response.getEntity();
        String result = "";
        if (entity != null) {
            result = EntityUtils.toString(entity, "utf-8");
            
        }
        httpPost.releaseConnection();
        return result;
    }

    public static String doGetString(String url) throws IOException {

        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
       
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        String result = "";
        if (entity != null) {
            result = EntityUtils.toString(entity, "utf-8");
           
        }
        httpGet.releaseConnection();
        return result;
    }

    /*public  User showUserById(String uid) throws WeiboException {
        org.json.JSONObject object = client.get(baseURL + "users/show.json",
            new PostParameter[]{new PostParameter("uid", uid)}).asJSONObject();
        System.out.println("==object=="+object+"==");
        return new User(object);
    }*/

    public Person showUserById(String uid) throws WeiboException {
        org.json.JSONObject object = client.get(baseURL + "users/show.json",
            new PostParameter[]{new PostParameter("uid", uid)}).asJSONObject();
        System.out.println("==object==" + object + "==");
        String s = org.json.JSONObject.valueToString(object);
        System.out.println("==s==" + s);
        JSONObject jsonObject = JSONObject.fromObject(s);
        System.out.println("==jsonobject--" + jsonObject);
        Person person = null;
        try {
            person = new Person(jsonObject);
            System.out.println("==person==" + person.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return person;
    }

    public static Map<String, Object> getAceessTokenByUid(String uid){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("http://127.0.0.1:8000/luaa/oauth/token");
        httpPost.setHeader("Accept", "application/json;charset=utf-8");
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        String uaaid = Base64.getEncoder().encodeToString("web_app:changeit".getBytes());
        httpPost.setHeader("Authorization", "Basic "+uaaid);
        httpPost.setHeader("custom_type","manage");
        CloseableHttpResponse response = null;
        //String params = "username=yewenjie&password=admin123&grant_type=password&client_secret=changeit&client_id=web_app&scope=openid";
        //String params = "username=123&password=admin12&grant_type=implicit&client_secret=changeit&client_id=web_app&scope=openid&auth_type=weibo";
        String params = "username="+uid+"&password=admin123&grant_type=password&auth_type=weibo";
        String charset = "utf-8";
        StringEntity se = new StringEntity(params,charset);
        httpPost.setEntity(se);
        //System.out.println("fuck...................");
        Map<String, Object> map = null;
        try {
            response = httpClient.execute(httpPost);
            String csrftoken = "";
            for(Header header: response.getAllHeaders()) {
                if("Set-Cookie".equals(header.getName())) {
                    csrftoken = header.getValue().split(";")[0].split("=")[1];
//            			System.out.println(csrftoken);
                    break;
                }
//            		System.out.println(header.getName()+" "+header.getValue());
            }
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            System.out.println("==state=="+state);

            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity);
                //System.out.println("************" + jsonString + "*********");
                map = (Map<String, Object>) JSONObject.toBean(JSONObject.fromObject(jsonString), HashMap.class);    
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return map;
    }

}

5 微博第三方登陆总结

请求流程:点击使用微博登陆按钮。会跳出一个授权页面,点击授权后,授权中心会返回uid,access_token等参数。本平台的后台程序通过uid到数据库中查找对应的账户信息。如果
	查找到了,准予登陆,系统跳转到首页。
		如果没有绑定,在登陆的时候会跳转到登陆并绑定页面。用户在页面输入账号和密码后会将参数传给平台后台(隐藏参数是uid)后台判断账号和密码的合法性(账号是否存在
		密码是否正确,账号是否激活等)。如果OK则进行绑定。绑定完成后跳转到平台首页。
	解绑:
		如果用户需要更换微博账号,则需要先解绑才能更换。解绑只需要在数据库中将对应账号和uid的关系删除即可。

在这次的实现过程中,遇到两个比较难解决的问题。一个是前后端分离以后,前台如何能接收到回调地址返回的结果。另一个是本次登陆集成在微服务中,微服务中因为有UAA在进行鉴权,所以如何通过用户唯一标识uid获取UAA分配的token(服务其它接口调用的必须参数)。因为oauth只支持五种授权码模式(implict,refresh_token,password,authorization_code,client_credentials),原本自己想实现一种新的授权码模式,即根据用户唯一标识来鉴权。后来等到实现的最后一步发现,如果想要行得通,必须得修改源码。所以后来经过讨论,通过另一种投机取巧的方式实现了。具体如下:授权码模式还是采用password,不过我们可以中间做些小改动,达到欺骗UAA鉴权的目的。那就是在拿到

UserDetailsService.loadUserByUsername(String username)返回结果之前将密码给定死,就欧克啦
Optional<User> userByQqidFromDatabase = userRepository.findOneWithAuthoritiesByQqidAndType(lowercaseLogin, type);
                org.springframework.security.core.userdetails.User u =  userByQqidFromDatabase.map(user -> createSpringSecurityUser2(lowercaseLogin, user))
                    .orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the " +
                        "database"));
                //System.out.println("==password=="+u.getPassword());
                People people = new People();
                people.setUsername(u.getUsername());
                people.setPassword(u.getPassword());
                people.setAuthorities(u.getAuthorities());
                //System.out.println("==people=="+people+"==:"+people.getPassword()+"==");
                people.setPassword("$2a$10$8EvwwWCHlRoJDpxyseR0Q.qgR2akWcrZw3ZGlwVZXFjl5QqWjThe.");
                //System.out.println("==people=="+people+"==:"+people.getPassword()+"==");

                return people;

猜你喜欢

转载自blog.csdn.net/kaichekaihanma/article/details/82798474