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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
智布道's avatar
智布道 已提交
5
import com.alibaba.fastjson.JSONPath;
6 7
import com.xkcoding.http.constants.Constants;
import com.xkcoding.http.support.HttpHeader;
8
import me.zhyd.oauth.cache.AuthStateCache;
9
import me.zhyd.oauth.config.AuthConfig;
10
import me.zhyd.oauth.config.AuthDefaultSource;
11
import me.zhyd.oauth.enums.AuthResponseStatus;
智布道's avatar
智布道 已提交
12
import me.zhyd.oauth.enums.AuthUserGender;
13
import me.zhyd.oauth.exception.AuthException;
14 15 16 17
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
18
import me.zhyd.oauth.utils.HttpUtils;
19
import me.zhyd.oauth.utils.StringUtils;
不合群的混子's avatar
不合群的混子 已提交
20
import me.zhyd.oauth.utils.UrlBuilder;
21 22 23 24 25 26


/**
 * 领英登录
 *
 * @author yadong.zhang (yadong.zhang0415(a)gmail.com)
智布道's avatar
智布道 已提交
27
 * @since 1.4.0
28
 */
智布道's avatar
智布道 已提交
29
public class AuthLinkedinRequest extends AuthDefaultRequest {
30 31

    public AuthLinkedinRequest(AuthConfig config) {
32
        super(config, AuthDefaultSource.LINKEDIN);
33 34
    }

35
    public AuthLinkedinRequest(AuthConfig config, AuthStateCache authStateCache) {
36
        super(config, AuthDefaultSource.LINKEDIN, authStateCache);
37 38
    }

39
    @Override
40
    protected AuthToken getAccessToken(AuthCallback authCallback) {
不合群的混子's avatar
不合群的混子 已提交
41
        return this.getToken(accessTokenUrl(authCallback.getCode()));
42 43 44 45 46
    }

    @Override
    protected AuthUser getUserInfo(AuthToken authToken) {
        String accessToken = authToken.getAccessToken();
47 48 49 50 51
        HttpHeader httpHeader = new HttpHeader();
        httpHeader.add("Host", "api.linkedin.com");
        httpHeader.add("Connection", "Keep-Alive");
        httpHeader.add("Authorization", "Bearer " + accessToken);

智布道's avatar
智布道 已提交
52
        String response = new HttpUtils(config.getHttpConfig()).get(userInfoUrl(authToken), null, httpHeader, false);
53
        JSONObject userInfoObject = JSONObject.parseObject(response);
54 55 56

        this.checkResponse(userInfoObject);

智布道's avatar
智布道 已提交
57 58 59 60 61 62 63 64
        String userName = getUserName(userInfoObject);

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

        // 获取用户邮箱地址
        String email = this.getUserEmail(accessToken);
        return AuthUser.builder()
65
            .rawUserInfo(userInfoObject)
智布道's avatar
智布道 已提交
66 67 68 69 70 71 72
            .uuid(userInfoObject.getString("id"))
            .username(userName)
            .nickname(userName)
            .avatar(avatar)
            .email(email)
            .token(authToken)
            .gender(AuthUserGender.UNKNOWN)
73
            .source(source.toString())
智布道's avatar
智布道 已提交
74 75 76 77 78 79 80 81 82 83
            .build();
    }

    /**
     * 获取用户的真实名
     *
     * @param userInfoObject 用户json对象
     * @return 用户名
     */
    private String getUserName(JSONObject userInfoObject) {
84 85 86 87 88 89 90 91 92 93 94 95 96
        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
智布道 已提交
97 98
        return firstName + " " + lastName;
    }
99

智布道's avatar
智布道 已提交
100 101 102 103 104 105 106
    /**
     * 获取用户的头像
     *
     * @param userInfoObject 用户json对象
     * @return 用户的头像地址
     */
    private String getAvatar(JSONObject userInfoObject) {
107
        JSONObject profilePictureObject = userInfoObject.getJSONObject("profilePicture");
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
        if (null == profilePictureObject || !profilePictureObject.containsKey("displayImage~")) {
            return null;
        }
        JSONObject displayImageObject = profilePictureObject.getJSONObject("displayImage~");
        if (null == displayImageObject || !displayImageObject.containsKey("elements")) {
            return null;
        }
        JSONArray displayImageElements = displayImageObject.getJSONArray("elements");
        if (null == displayImageElements || displayImageElements.isEmpty()) {
            return null;
        }
        JSONObject largestImageObj = displayImageElements.getJSONObject(displayImageElements.size() - 1);
        if (null == largestImageObj || !largestImageObj.containsKey("identifiers")) {
            return null;
        }
        JSONArray identifiers = largestImageObj.getJSONArray("identifiers");
        if (null == identifiers || identifiers.isEmpty()) {
            return null;
126
        }
127
        return identifiers.getJSONObject(0).getString("identifier");
128 129
    }

智布道's avatar
智布道 已提交
130 131 132 133 134 135
    /**
     * 获取用户的email
     *
     * @param accessToken 用户授权后返回的token
     * @return 用户的邮箱地址
     */
136
    private String getUserEmail(String accessToken) {
137 138 139 140 141
        HttpHeader httpHeader = new HttpHeader();
        httpHeader.add("Host", "api.linkedin.com");
        httpHeader.add("Connection", "Keep-Alive");
        httpHeader.add("Authorization", "Bearer " + accessToken);

智布道's avatar
智布道 已提交
142
        String emailResponse = new HttpUtils(config.getHttpConfig()).get("https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))", null, httpHeader, false);
143 144
        JSONObject emailObj = JSONObject.parseObject(emailResponse);

智布道's avatar
智布道 已提交
145
        this.checkResponse(emailObj);
146

智布道's avatar
智布道 已提交
147 148
        Object obj = JSONPath.eval(emailObj, "$['elements'][0]['handle~']['emailAddress']");
        return null == obj ? null : (String) obj;
149 150 151 152 153 154 155 156 157 158 159
    }

    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;
    }

智布道's avatar
智布道 已提交
160 161 162 163 164 165 166
    /**
     * 检查响应内容是否正确
     *
     * @param object 请求响应内容
     */
    private void checkResponse(JSONObject object) {
        if (object.containsKey("error")) {
智布道's avatar
智布道 已提交
167
            throw new AuthException(object.getString("error_description"), source);
168 169 170 171 172 173 174 175 176 177
        }
    }

    /**
     * 获取token,适用于获取access_token和刷新token
     *
     * @param accessTokenUrl 实际请求token的地址
     * @return token对象
     */
    private AuthToken getToken(String accessTokenUrl) {
178 179 180 181
        HttpHeader httpHeader = new HttpHeader();
        httpHeader.add("Host", "www.linkedin.com");
        httpHeader.add(Constants.CONTENT_TYPE, "application/x-www-form-urlencoded");

智布道's avatar
智布道 已提交
182
        String response = new HttpUtils(config.getHttpConfig()).post(accessTokenUrl, null, httpHeader);
183
        JSONObject accessTokenObject = JSONObject.parseObject(response);
184 185 186 187

        this.checkResponse(accessTokenObject);

        return AuthToken.builder()
不合群的混子's avatar
不合群的混子 已提交
188 189 190 191 192 193 194
            .accessToken(accessTokenObject.getString("access_token"))
            .expireIn(accessTokenObject.getIntValue("expires_in"))
            .refreshToken(accessTokenObject.getString("refresh_token"))
            .build();
    }

    /**
195
     * 返回带{@code state}参数的授权url,授权回调时会带上这个{@code state}
不合群的混子's avatar
不合群的混子 已提交
196
     *
197
     * @param state state 验证授权流程的参数,可以防止csrf
不合群的混子's avatar
不合群的混子 已提交
198
     * @return 返回授权地址
智布道's avatar
智布道 已提交
199
     * @since 1.9.3
不合群的混子's avatar
不合群的混子 已提交
200 201
     */
    @Override
202
    public String authorize(String state) {
不合群的混子's avatar
不合群的混子 已提交
203 204 205 206 207
        return UrlBuilder.fromBaseUrl(source.authorize())
            .queryParam("response_type", "code")
            .queryParam("client_id", config.getClientId())
            .queryParam("redirect_uri", config.getRedirectUri())
            .queryParam("scope", "r_liteprofile%20r_emailaddress%20w_member_social")
208
            .queryParam("state", getRealState(state))
不合群的混子's avatar
不合群的混子 已提交
209 210 211 212 213 214
            .build();
    }

    /**
     * 返回获取userInfo的url
     *
215
     * @param authToken 用户授权后的token
不合群的混子's avatar
不合群的混子 已提交
216 217 218 219 220 221 222
     * @return 返回获取userInfo的url
     */
    @Override
    protected String userInfoUrl(AuthToken authToken) {
        return UrlBuilder.fromBaseUrl(source.userInfo())
            .queryParam("projection", "(id,firstName,lastName,profilePicture(displayImage~:playableStreams))")
            .build();
223 224
    }
}