AuthLinkedinRequest.java 7.4 KB
Newer Older
1 2 3 4 5 6
package me.zhyd.oauth.request;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
智布道's avatar
智布道 已提交
7
import com.alibaba.fastjson.JSONPath;
8
import me.zhyd.oauth.config.AuthConfig;
9
import me.zhyd.oauth.config.AuthSource;
智布道's avatar
智布道 已提交
10
import me.zhyd.oauth.enums.AuthUserGender;
11
import me.zhyd.oauth.exception.AuthException;
12
import me.zhyd.oauth.model.*;
13
import me.zhyd.oauth.utils.StringUtils;
不合群的混子's avatar
不合群的混子 已提交
14
import me.zhyd.oauth.utils.UrlBuilder;
15 16 17 18 19 20 21 22 23


/**
 * 领英登录
 *
 * @author yadong.zhang (yadong.zhang0415(a)gmail.com)
 * @version 1.0
 * @since 1.8
 */
智布道's avatar
智布道 已提交
24
public class AuthLinkedinRequest extends AuthDefaultRequest {
25 26

    public AuthLinkedinRequest(AuthConfig config) {
不合群的混子's avatar
不合群的混子 已提交
27
        super(config, AuthSource.LINKEDIN);
28 29 30
    }

    @Override
31
    protected AuthToken getAccessToken(AuthCallback authCallback) {
不合群的混子's avatar
不合群的混子 已提交
32
        return this.getToken(accessTokenUrl(authCallback.getCode()));
33 34 35 36 37
    }

    @Override
    protected AuthUser getUserInfo(AuthToken authToken) {
        String accessToken = authToken.getAccessToken();
不合群的混子's avatar
不合群的混子 已提交
38 39 40 41 42
        HttpResponse response = HttpRequest.get(userInfoUrl(authToken))
            .header("Host", "api.linkedin.com")
            .header("Connection", "Keep-Alive")
            .header("Authorization", "Bearer " + accessToken)
            .execute();
43 44 45 46
        JSONObject userInfoObject = JSONObject.parseObject(response.body());

        this.checkResponse(userInfoObject);

智布道's avatar
智布道 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
        String userName = getUserName(userInfoObject);

        // 获取用户头像
        String avatar = this.getAvatar(userInfoObject);

        // 获取用户邮箱地址
        String email = this.getUserEmail(accessToken);
        return AuthUser.builder()
            .uuid(userInfoObject.getString("id"))
            .username(userName)
            .nickname(userName)
            .avatar(avatar)
            .email(email)
            .token(authToken)
            .gender(AuthUserGender.UNKNOWN)
            .source(AuthSource.LINKEDIN)
            .build();
    }

    /**
     * 获取用户的真实名
     *
     * @param userInfoObject 用户json对象
     * @return 用户名
     */
    private String getUserName(JSONObject userInfoObject) {
73 74 75 76 77 78 79 80 81 82 83 84 85
        String firstName, lastName;
        // 获取firstName
        if (userInfoObject.containsKey("localizedFirstName")) {
            firstName = userInfoObject.getString("localizedFirstName");
        } else {
            firstName = getUserName(userInfoObject, "firstName");
        }
        // 获取lastName
        if (userInfoObject.containsKey("localizedLastName")) {
            lastName = userInfoObject.getString("localizedLastName");
        } else {
            lastName = getUserName(userInfoObject, "lastName");
        }
智布道's avatar
智布道 已提交
86 87
        return firstName + " " + lastName;
    }
88

智布道's avatar
智布道 已提交
89 90 91 92 93 94 95
    /**
     * 获取用户的头像
     *
     * @param userInfoObject 用户json对象
     * @return 用户的头像地址
     */
    private String getAvatar(JSONObject userInfoObject) {
96 97 98
        String avatar = null;
        JSONObject profilePictureObject = userInfoObject.getJSONObject("profilePicture");
        if (profilePictureObject.containsKey("displayImage~")) {
99
            JSONArray displayImageElements = profilePictureObject.getJSONObject("displayImage~")
不合群的混子's avatar
不合群的混子 已提交
100
                .getJSONArray("elements");
101 102 103 104 105
            if (null != displayImageElements && displayImageElements.size() > 0) {
                JSONObject largestImageObj = displayImageElements.getJSONObject(displayImageElements.size() - 1);
                avatar = largestImageObj.getJSONArray("identifiers").getJSONObject(0).getString("identifier");
            }
        }
智布道's avatar
智布道 已提交
106
        return avatar;
107 108
    }

智布道's avatar
智布道 已提交
109 110 111 112 113 114
    /**
     * 获取用户的email
     *
     * @param accessToken 用户授权后返回的token
     * @return 用户的邮箱地址
     */
115 116 117
    private String getUserEmail(String accessToken) {
        String email = null;
        HttpResponse emailResponse = HttpRequest.get("https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))")
不合群的混子's avatar
不合群的混子 已提交
118 119 120 121
            .header("Host", "api.linkedin.com")
            .header("Connection", "Keep-Alive")
            .header("Authorization", "Bearer " + accessToken)
            .execute();
122
        JSONObject emailObj = JSONObject.parseObject(emailResponse.body());
智布道's avatar
智布道 已提交
123
        this.checkResponse(emailObj);
智布道's avatar
智布道 已提交
124 125
        Object obj = JSONPath.eval(emailObj, "$['elements'][0]['handle~']['emailAddress']");
        return null == obj ? null : (String) obj;
126 127 128 129 130 131 132 133 134 135 136 137 138
    }

    private String getUserName(JSONObject userInfoObject, String nameKey) {
        String firstName;
        JSONObject firstNameObj = userInfoObject.getJSONObject(nameKey);
        JSONObject localizedObj = firstNameObj.getJSONObject("localized");
        JSONObject preferredLocaleObj = firstNameObj.getJSONObject("preferredLocale");
        firstName = localizedObj.getString(preferredLocaleObj.getString("language") + "_" + preferredLocaleObj.getString("country"));
        return firstName;
    }

    @Override
    public AuthResponse refresh(AuthToken oldToken) {
不合群的混子's avatar
不合群的混子 已提交
139 140
        String refreshToken = oldToken.getRefreshToken();
        if (StringUtils.isEmpty(refreshToken)) {
智布道's avatar
智布道 已提交
141
            throw new AuthException(AuthResponseStatus.UNSUPPORTED);
142
        }
不合群的混子's avatar
不合群的混子 已提交
143
        String refreshTokenUrl = refreshTokenUrl(refreshToken);
144
        return AuthResponse.builder()
不合群的混子's avatar
不合群的混子 已提交
145 146 147
            .code(AuthResponseStatus.SUCCESS.getCode())
            .data(this.getToken(refreshTokenUrl))
            .build();
148 149
    }

智布道's avatar
智布道 已提交
150 151 152 153 154 155 156 157
    /**
     * 检查响应内容是否正确
     *
     * @param object 请求响应内容
     */
    private void checkResponse(JSONObject object) {
        if (object.containsKey("error")) {
            throw new AuthException(object.getString("error_description"));
158 159 160 161 162 163 164 165 166 167 168
        }
    }

    /**
     * 获取token,适用于获取access_token和刷新token
     *
     * @param accessTokenUrl 实际请求token的地址
     * @return token对象
     */
    private AuthToken getToken(String accessTokenUrl) {
        HttpResponse response = HttpRequest.post(accessTokenUrl)
不合群的混子's avatar
不合群的混子 已提交
169
            .header("Host", "www.linkedin.com")
170
            .contentType("application/x-www-form-urlencoded")
不合群的混子's avatar
不合群的混子 已提交
171
            .execute();
172 173 174 175 176 177
        String accessTokenStr = response.body();
        JSONObject accessTokenObject = JSONObject.parseObject(accessTokenStr);

        this.checkResponse(accessTokenObject);

        return AuthToken.builder()
不合群的混子's avatar
不合群的混子 已提交
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
            .accessToken(accessTokenObject.getString("access_token"))
            .expireIn(accessTokenObject.getIntValue("expires_in"))
            .refreshToken(accessTokenObject.getString("refresh_token"))
            .build();
    }

    /**
     * 返回认证url,可自行跳转页面
     *
     * @return 返回授权地址
     */
    @Override
    public String authorize() {
        return UrlBuilder.fromBaseUrl(source.authorize())
            .queryParam("response_type", "code")
            .queryParam("client_id", config.getClientId())
            .queryParam("redirect_uri", config.getRedirectUri())
            .queryParam("state", getRealState(config.getState()))
            .queryParam("scope", "r_liteprofile%20r_emailaddress%20w_member_social")
            .build();
    }

    /**
     * 返回获取userInfo的url
     *
203
     * @param authToken 用户授权后的token
不合群的混子's avatar
不合群的混子 已提交
204 205 206 207 208 209 210
     * @return 返回获取userInfo的url
     */
    @Override
    protected String userInfoUrl(AuthToken authToken) {
        return UrlBuilder.fromBaseUrl(source.userInfo())
            .queryParam("projection", "(id,firstName,lastName,profilePicture(displayImage~:playableStreams))")
            .build();
211 212
    }
}