AuthLinkedinRequest.java 6.8 KB
Newer Older
1 2 3 4 5 6 7
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;
import me.zhyd.oauth.config.AuthConfig;
8
import me.zhyd.oauth.config.AuthSource;
9
import me.zhyd.oauth.exception.AuthException;
10
import me.zhyd.oauth.model.*;
11
import me.zhyd.oauth.utils.StringUtils;
不合群的混子's avatar
不合群的混子 已提交
12
import me.zhyd.oauth.utils.UrlBuilder;
13 14 15 16 17 18 19 20 21


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

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

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

    @Override
    protected AuthUser getUserInfo(AuthToken authToken) {
        String accessToken = authToken.getAccessToken();
不合群的混子's avatar
不合群的混子 已提交
36 37 38 39 40
        HttpResponse response = HttpRequest.get(userInfoUrl(authToken))
            .header("Host", "api.linkedin.com")
            .header("Connection", "Keep-Alive")
            .header("Authorization", "Bearer " + accessToken)
            .execute();
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
        JSONObject userInfoObject = JSONObject.parseObject(response.body());

        this.checkResponse(userInfoObject);

        // 组装用户名
        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");
        }
        String userName = firstName + " " + lastName;

        // 获取用户头像
        String avatar = null;
        JSONObject profilePictureObject = userInfoObject.getJSONObject("profilePicture");
        if (profilePictureObject.containsKey("displayImage~")) {
65
            JSONArray displayImageElements = profilePictureObject.getJSONObject("displayImage~")
不合群的混子's avatar
不合群的混子 已提交
66
                .getJSONArray("elements");
67 68 69 70 71 72 73 74 75
            if (null != displayImageElements && displayImageElements.size() > 0) {
                JSONObject largestImageObj = displayImageElements.getJSONObject(displayImageElements.size() - 1);
                avatar = largestImageObj.getJSONArray("identifiers").getJSONObject(0).getString("identifier");
            }
        }

        // 获取用户邮箱地址
        String email = this.getUserEmail(accessToken);
        return AuthUser.builder()
不合群的混子's avatar
不合群的混子 已提交
76 77 78 79 80 81 82 83 84
            .uuid(userInfoObject.getString("id"))
            .username(userName)
            .nickname(userName)
            .avatar(avatar)
            .email(email)
            .token(authToken)
            .gender(AuthUserGender.UNKNOWN)
            .source(AuthSource.LINKEDIN)
            .build();
85 86 87 88 89
    }

    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
不合群的混子 已提交
90 91 92 93
            .header("Host", "api.linkedin.com")
            .header("Connection", "Keep-Alive")
            .header("Authorization", "Bearer " + accessToken)
            .execute();
94 95 96
        System.out.println(emailResponse.body());
        JSONObject emailObj = JSONObject.parseObject(emailResponse.body());
        if (emailObj.containsKey("elements")) {
97
            email = emailObj.getJSONArray("elements")
不合群的混子's avatar
不合群的混子 已提交
98 99 100
                .getJSONObject(0)
                .getJSONObject("handle~")
                .getString("emailAddress");
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
        }
        return email;
    }

    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
不合群的混子 已提交
116 117
        String refreshToken = oldToken.getRefreshToken();
        if (StringUtils.isEmpty(refreshToken)) {
智布道's avatar
智布道 已提交
118
            throw new AuthException(AuthResponseStatus.UNSUPPORTED);
119
        }
不合群的混子's avatar
不合群的混子 已提交
120
        String refreshTokenUrl = refreshTokenUrl(refreshToken);
121
        return AuthResponse.builder()
不合群的混子's avatar
不合群的混子 已提交
122 123 124
            .code(AuthResponseStatus.SUCCESS.getCode())
            .data(this.getToken(refreshTokenUrl))
            .build();
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
    }

    private void checkResponse(JSONObject userInfoObject) {
        if (userInfoObject.containsKey("error")) {
            throw new AuthException(userInfoObject.getString("error_description"));
        }
    }

    /**
     * 获取token,适用于获取access_token和刷新token
     *
     * @param accessTokenUrl 实际请求token的地址
     * @return token对象
     */
    private AuthToken getToken(String accessTokenUrl) {
        HttpResponse response = HttpRequest.post(accessTokenUrl)
不合群的混子's avatar
不合群的混子 已提交
141 142 143
            .header("Host", "www.linkedin.com")
            .header("Content-Type", "application/x-www-form-urlencoded")
            .execute();
144 145 146 147 148 149
        String accessTokenStr = response.body();
        JSONObject accessTokenObject = JSONObject.parseObject(accessTokenStr);

        this.checkResponse(accessTokenObject);

        return AuthToken.builder()
不合群的混子's avatar
不合群的混子 已提交
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
            .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
     *
     * @param authToken
     * @return 返回获取userInfo的url
     */
    @Override
    protected String userInfoUrl(AuthToken authToken) {
        return UrlBuilder.fromBaseUrl(source.userInfo())
            .queryParam("projection", "(id,firstName,lastName,profilePicture(displayImage~:playableStreams))")
            .build();
183 184
    }
}