com.flyfish.oauth.entry.scribe.DynamicOAuth20Service Maven / Gradle / Ivy
package com.flyfish.oauth.entry.scribe;
import com.flyfish.oauth.utils.JacksonUtil;
import com.github.scribejava.core.builder.api.DefaultApi20;
import com.github.scribejava.core.httpclient.HttpClient;
import com.github.scribejava.core.httpclient.HttpClientConfig;
import com.github.scribejava.core.model.OAuthRequest;
import com.github.scribejava.core.model.Response;
import com.github.scribejava.core.model.Verb;
import com.github.scribejava.core.oauth.OAuth20Service;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.concurrent.ExecutionException;
/**
* 自定义的动态OAuth服务
*
* @author wybab
*/
public class DynamicOAuth20Service extends OAuth20Service {
private ThreadLocal callback = new ThreadLocal<>();
private SecurityServerApi api;
public DynamicOAuth20Service(DefaultApi20 api, String apiKey, String apiSecret, String callback, String defaultScope,
String responseType, String userAgent, HttpClientConfig httpClientConfig, HttpClient httpClient) {
super(api, apiKey, apiSecret, callback, defaultScope, responseType, userAgent, httpClientConfig, httpClient);
this.api = (SecurityServerApi) api;
}
@Override
public String getCallback() {
return this.callback.get();
}
/**
* 检查accessToken
*
* @param accessToken 访问凭据
* @return 结果
* @throws InterruptedException 中断异常
* @throws ExecutionException 执行异常
* @throws IOException 输入输出异常
*/
public CheckTokenResult checkAccessToken(String accessToken) throws InterruptedException, ExecutionException, IOException {
OAuthRequest request = createCheckTokenRequest(accessToken);
Response response = execute(request);
if (StringUtils.isNotBlank(response.getBody())) {
return JacksonUtil.fromJson(response.getBody(), CheckTokenResult.class);
}
return CheckTokenResult.empty();
}
public DynamicOAuth20Service withCallback(String callback) {
String originUrl = extractOriginUrl(callback);
this.callback.set(api.getProperties().getRedirectUri() + originUrl);
return this;
}
/**
* 解压源URL
*
* @param redirect 源
* @return 结果
*/
private String extractOriginUrl(String redirect) {
String callbackUrl;
try {
callbackUrl = StringUtils.isBlank(redirect) ? "" :
("?redirect=" + URLEncoder.encode(redirect, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
callbackUrl = "";
}
return callbackUrl;
}
/**
* 检查Token
*
* @param token token
* @return 结果
*/
protected OAuthRequest createCheckTokenRequest(String token) {
final OAuthRequest request = new OAuthRequest(Verb.GET, api.getProperties().getCheckAccessTokenUri());
api.getClientAuthentication().addClientAuthentication(request, getApiKey(), getApiSecret());
request.addParameter("token", token);
return request;
}
}