AuthCsdnRequest.java 1.9 KB
Newer Older
1 2 3 4 5 6 7 8
package me.zhyd.oauth.request;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthSource;
9
import me.zhyd.oauth.model.AuthToken;
10 11 12 13
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.utils.UrlBuilder;

/**
14 15
 * CSDN登录
 *
16 17 18 19 20 21 22 23 24 25 26
 * @author yadong.zhang (yadong.zhang0415(a)gmail.com)
 * @version 1.0
 * @since 1.8
 */
public class AuthCsdnRequest extends BaseAuthRequest {

    public AuthCsdnRequest(AuthConfig config) {
        super(config, AuthSource.CSDN);
    }

    @Override
27
    protected AuthToken getAccessToken(String code) {
28 29 30 31 32 33
        String accessTokenUrl = UrlBuilder.getCsdnAccessTokenUrl(config.getClientId(), config.getClientSecret(), code, config.getRedirectUri());
        HttpResponse response = HttpRequest.post(accessTokenUrl).execute();
        JSONObject accessTokenObject = JSONObject.parseObject(response.body());
        if (accessTokenObject.containsKey("error_code")) {
            throw new AuthException("Unable to get token from csdn using code [" + code + "]");
        }
34 35 36
        return AuthToken.builder()
                .accessToken(accessTokenObject.getString("access_token"))
                .build();
37 38 39
    }

    @Override
40 41
    protected AuthUser getUserInfo(AuthToken authToken) {
        String accessToken = authToken.getAccessToken();
42 43 44 45 46 47 48
        HttpResponse response = HttpRequest.get(UrlBuilder.getCsdnUserInfoUrl(accessToken)).execute();
        JSONObject object = JSONObject.parseObject(response.body());
        if (object.containsKey("error_code")) {
            throw new AuthException(object.getString("error"));
        }
        return AuthUser.builder()
                .username(object.getString("username"))
49
                .token(authToken)
50 51 52 53
                .source(AuthSource.CSDN)
                .build();
    }
}