You need to sign in or sign up before continuing.
AuthLinkedinRequest.java 8.1 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;
智布道's avatar
智布道 已提交
11
import me.zhyd.oauth.enums.AuthUserGender;
12
import me.zhyd.oauth.enums.scope.AuthLinkedinScope;
13
import me.zhyd.oauth.exception.AuthException;
14 15 16
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
17
import me.zhyd.oauth.utils.HttpUtils;
不合群的混子's avatar
不合群的混子 已提交
18
import me.zhyd.oauth.utils.UrlBuilder;
19 20 21 22 23 24


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

    public AuthLinkedinRequest(AuthConfig config) {
30
        super(config, AuthDefaultSource.LINKEDIN);
31 32
    }

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

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

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

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

        this.checkResponse(userInfoObject);

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

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

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

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

智布道's avatar
智布道 已提交
98 99 100 101 102 103 104
    /**
     * 获取用户的头像
     *
     * @param userInfoObject 用户json对象
     * @return 用户的头像地址
     */
    private String getAvatar(JSONObject userInfoObject) {
105
        JSONObject profilePictureObject = userInfoObject.getJSONObject("profilePicture");
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
        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;
124
        }
125
        return identifiers.getJSONObject(0).getString("identifier");
126 127
    }

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

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

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

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

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

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

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

        this.checkResponse(accessTokenObject);

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

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

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