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;
智布道's avatar
智布道 已提交
6
import me.zhyd.oauth.utils.HttpUtils;
7 8
import com.xkcoding.http.constants.Constants;
import com.xkcoding.http.support.HttpHeader;
9
import me.zhyd.oauth.cache.AuthStateCache;
10
import me.zhyd.oauth.config.AuthConfig;
11
import me.zhyd.oauth.config.AuthDefaultSource;
12
import me.zhyd.oauth.enums.AuthResponseStatus;
智布道's avatar
智布道 已提交
13
import me.zhyd.oauth.enums.AuthUserGender;
14
import me.zhyd.oauth.exception.AuthException;
15 16 17 18
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
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 65 66 67 68 69 70 71
        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)
72
            .source(source.toString())
智布道's avatar
智布道 已提交
73 74 75 76 77 78 79 80 81 82
            .build();
    }

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

智布道's avatar
智布道 已提交
99 100 101 102 103 104 105
    /**
     * 获取用户的头像
     *
     * @param userInfoObject 用户json对象
     * @return 用户的头像地址
     */
    private String getAvatar(JSONObject userInfoObject) {
106 107 108
        String avatar = null;
        JSONObject profilePictureObject = userInfoObject.getJSONObject("profilePicture");
        if (profilePictureObject.containsKey("displayImage~")) {
109
            JSONArray displayImageElements = profilePictureObject.getJSONObject("displayImage~")
不合群的混子's avatar
不合群的混子 已提交
110
                .getJSONArray("elements");
111 112 113 114 115
            if (null != displayImageElements && displayImageElements.size() > 0) {
                JSONObject largestImageObj = displayImageElements.getJSONObject(displayImageElements.size() - 1);
                avatar = largestImageObj.getJSONArray("identifiers").getJSONObject(0).getString("identifier");
            }
        }
智布道's avatar
智布道 已提交
116
        return avatar;
117 118
    }

智布道's avatar
智布道 已提交
119 120 121 122 123 124
    /**
     * 获取用户的email
     *
     * @param accessToken 用户授权后返回的token
     * @return 用户的邮箱地址
     */
125
    private String getUserEmail(String accessToken) {
126 127 128 129 130
        HttpHeader httpHeader = new HttpHeader();
        httpHeader.add("Host", "api.linkedin.com");
        httpHeader.add("Connection", "Keep-Alive");
        httpHeader.add("Authorization", "Bearer " + accessToken);

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

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

智布道's avatar
智布道 已提交
136 137
        Object obj = JSONPath.eval(emailObj, "$['elements'][0]['handle~']['emailAddress']");
        return null == obj ? null : (String) obj;
138 139 140 141 142 143 144 145 146 147 148 149 150
    }

    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
不合群的混子 已提交
151 152
        String refreshToken = oldToken.getRefreshToken();
        if (StringUtils.isEmpty(refreshToken)) {
智布道's avatar
智布道 已提交
153
            throw new AuthException(AuthResponseStatus.REQUIRED_REFRESH_TOKEN, source);
154
        }
不合群的混子's avatar
不合群的混子 已提交
155
        String refreshTokenUrl = refreshTokenUrl(refreshToken);
156
        return AuthResponse.builder()
不合群的混子's avatar
不合群的混子 已提交
157 158 159
            .code(AuthResponseStatus.SUCCESS.getCode())
            .data(this.getToken(refreshTokenUrl))
            .build();
160 161
    }

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

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

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

        this.checkResponse(accessTokenObject);

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

    /**
197
     * 返回带{@code state}参数的授权url,授权回调时会带上这个{@code state}
不合群的混子's avatar
不合群的混子 已提交
198
     *
199
     * @param state state 验证授权流程的参数,可以防止csrf
不合群的混子's avatar
不合群的混子 已提交
200
     * @return 返回授权地址
智布道's avatar
智布道 已提交
201
     * @since 1.9.3
不合群的混子's avatar
不合群的混子 已提交
202 203
     */
    @Override
204
    public String authorize(String state) {
不合群的混子's avatar
不合群的混子 已提交
205 206 207 208 209
        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")
210
            .queryParam("state", getRealState(state))
不合群的混子's avatar
不合群的混子 已提交
211 212 213 214 215 216
            .build();
    }

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