本文整理汇总了Java中com.github.scribejava.core.oauth.OAuth20Service.signRequest方法的典型用法代码示例。如果您正苦于以下问题:Java OAuth20Service.signRequest方法的具体用法?Java OAuth20Service.signRequest怎么用?Java OAuth20Service.signRequest使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类com.github.scribejava.core.oauth.OAuth20Service
的用法示例。
在下文中一共展示了OAuth20Service.signRequest方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: main
import com.github.scribejava.core.oauth.OAuth20Service; //导入方法依赖的package包/类
public static void main (String[] args) {
ResourceBundle secrets = ResourceBundle.getBundle("facebookutil/secret");
final OAuth20Service service = new ServiceBuilder()
.apiKey(secrets.getString("clientId"))
.apiSecret(secrets.getString("clientSecret"))
.callback("https://duke.edu/")
.grantType("client_credentials")
.build(FacebookApi.instance());
String url = "https://graph.facebook.com/oauth/access_token?";
url = url + "&client_id" + "=" + secrets.getString("clientId");
url = url + "&client_secret" + "=" + secrets.getString("clientSecret");
url = url + "&grant_type" + "=" + "client_credentials";
final OAuthRequest request =
new OAuthRequest(Verb.GET, url, service);
service.signRequest(new OAuth2AccessToken(""), request);
System.out.println(request.getBodyContents());
System.out.println(request.getUrl());
Response response = request.send();
System.out.println(response.getBody());
}
示例2: validate
import com.github.scribejava.core.oauth.OAuth20Service; //导入方法依赖的package包/类
@Override
public CredentialValidationResult validate(Credential credential) {
if (credential instanceof TokenResponseCredential) {
TokenResponseCredential tokenCredential = (TokenResponseCredential) credential;
OAuthRequest request = new OAuthRequest(Verb.GET, "https://www.googleapis.com/oauth2/v3/userinfo");
OAuth20Service service = tokenCredential.getService();
OAuth2AccessToken token = tokenCredential.getTokenResponse();
service.signRequest(token, request);
try {
Response oResp = service.execute(request);
String body = oResp.getBody();
OAuth2User oAuth2User = jsonProcessor.extractUserInfo(body);
return new CredentialValidationResult(oAuth2User);
} catch (InterruptedException | ExecutionException | IOException e) {
e.printStackTrace(); // FIXME
}
}
return CredentialValidationResult.NOT_VALIDATED_RESULT;
}
示例3: processRequest
import com.github.scribejava.core.oauth.OAuth20Service; //导入方法依赖的package包/类
private void processRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String code = req.getParameter("code");
LOGGER.info("OAuth2 code: [{}]", code);
String provider = StringUtils.substringAfterLast(req.getRequestURI(), "/");
LOGGER.info("Provider: [{}]", provider);
OAuth20Service oAuth2Service = this.providerFactory.getOAuth2Service(provider);
OAuth2AccessToken token = null;
try {
token = oAuth2Service.getAccessToken(code);
LOGGER.info("OAuth2AccessToken: [{}]", token);
OAuthRequest oReq = new OAuthRequest(Verb.GET, "https://api.linkedin.com/v1/people/~?format=json");
oAuth2Service.signRequest(token, oReq);
Response oResp = oAuth2Service.execute(oReq);
LOGGER.info("Linkedin Profile: [{}]", oResp.getBody());
resp.getOutputStream().write(oResp.getBody().getBytes(StandardCharsets.UTF_8));
} catch (InterruptedException | ExecutionException ex) {
}
}
示例4: isOrganizationMember
import com.github.scribejava.core.oauth.OAuth20Service; //导入方法依赖的package包/类
/**
* Check to see that login is a member of organization.
*
* A 204 response code indicates organization membership. 302 and 404 codes are not treated as exceptional,
* they indicate various ways in which a login is not a member of the organization.
*
* @see <a href="https://developer.github.com/v3/orgs/members/#response-if-requester-is-an-organization-member-and-user-is-a-member">GitHub members API</a>
*/
private boolean isOrganizationMember(OAuth2AccessToken accessToken, String organization, String login) throws IOException, ExecutionException, InterruptedException {
String requestUrl = settings.apiURL() + format("orgs/%s/members/%s", organization, login);
OAuth20Service scribe = new ServiceBuilder(settings.clientId())
.apiSecret(settings.clientSecret())
.build(scribeApi);
OAuthRequest request = new OAuthRequest(Verb.GET, requestUrl);
scribe.signRequest(accessToken, request);
Response response = scribe.execute(request);
int code = response.getCode();
switch (code) {
case HttpURLConnection.HTTP_MOVED_TEMP:
case HttpURLConnection.HTTP_NOT_FOUND:
case HttpURLConnection.HTTP_NO_CONTENT:
LOGGER.trace("Orgs response received : {}", code);
return code == HttpURLConnection.HTTP_NO_CONTENT;
default:
throw unexpectedResponseCode(requestUrl, response);
}
}
示例5: callback
import com.github.scribejava.core.oauth.OAuth20Service; //导入方法依赖的package包/类
@Override
public void callback(CallbackContext context) {
context.verifyCsrfState();
HttpServletRequest request = context.getRequest();
OAuth20Service scribe = prepareScribe(context).build(GoogleApi20.instance());
String oAuthVerifier = request.getParameter("code");
OAuth2AccessToken accessToken = scribe.getAccessToken(new Verifier(oAuthVerifier));
OAuthRequest userRequest = new OAuthRequest(Verb.GET, "https://www.googleapis.com/oauth2/v2/userinfo", scribe);
scribe.signRequest(accessToken, userRequest);
com.github.scribejava.core.model.Response userResponse = userRequest.send();
if (!userResponse.isSuccessful()) {
throw new IllegalStateException(format("Fail to authenticate the user. Error code is %s, Body of the response is %s",
userResponse.getCode(), userResponse.getBody()));
}
String userResponseBody = userResponse.getBody();
LOGGER.trace("User response received : %s", userResponseBody);
GsonUser gsonUser = GsonUser.parse(userResponseBody);
UserIdentity userIdentity = UserIdentity.builder()
.setProviderLogin(gsonUser.getEmail())
.setLogin(gsonUser.getEmail())
.setName(gsonUser.getName())
.setEmail(gsonUser.getEmail())
.build();
context.authenticate(userIdentity);
context.redirectToRequestedPage();
}
示例6: getOpenId
import com.github.scribejava.core.oauth.OAuth20Service; //导入方法依赖的package包/类
public String getOpenId(OAuth2AccessToken accessToken, OAuth20Service service) {
final OAuthRequest request = new OAuthRequest(Verb.GET, GET_OPEN_ID_URL, service);
service.signRequest(accessToken, request);
Response response = request.send();
String rawResponse = null;
try {
rawResponse = response.getBody();
} catch (IOException e) {
}
String formattedStr = rawResponse.substring(rawResponse.indexOf("{"), rawResponse.indexOf("}") + 1);
return JsonUtil.getString("openid", formattedStr);
}
示例7: authenticated
import com.github.scribejava.core.oauth.OAuth20Service; //导入方法依赖的package包/类
@Override
public GatewayResponse authenticated(String state, String code) {
OAuth20Service service = getOAuthServiceProvider(state);
GatewayAccessToken accessToken = getAccessToken(state, code);
checkToken(accessToken);
String openId = getOpenId(accessToken, service);
EventPublisher.instance().publishEvent(new AccessTokenRetrievedEvent(state, accessToken));
final OAuthRequest request = new OAuthRequest(Verb.GET,
getUserInfoUrl() + "?oauth_consumer_key=" + qqConfig.getApiKey() + "&openid=" + openId, service);
service.signRequest(accessToken, request);
Response response = request.send();
return parseUserInfoResponse(response);
}
示例8: retrieveUserInfo
import com.github.scribejava.core.oauth.OAuth20Service; //导入方法依赖的package包/类
protected GatewayResponse retrieveUserInfo(GatewayAccessToken accessToken, OAuth20Service service) {
String userInfoUrl = getUserInfoUrl() + getAppendedUrl(accessToken);
final OAuthRequest request = new OAuthRequest(Verb.GET, userInfoUrl, service);
service.signRequest(accessToken, request);
Response response = request.send();
return parseUserInfoResponse(response);
}
示例9: processRequest
import com.github.scribejava.core.oauth.OAuth20Service; //导入方法依赖的package包/类
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws IOException, InterruptedException, ExecutionException, JSONException, SQLException, NamingException, ClassNotFoundException {
String glgCode = request.getParameter("code");
//System.out.println(FacesContext.getCurrentInstance().getExternalContext());
if (glgCode != null) {
//System.out.println("GoogleCallback glgCode=" + glgCode);
HttpSession session = request.getSession(true);
OAuth20Service service = (OAuth20Service) session.getAttribute("oauth2Service");
if (service != null) {
//Construct the access token
OAuth2AccessToken accessToken = service.getAccessToken(glgCode);
//System.out.println("Got the Access Token!");
//Save the token for the duration of the session
session.setAttribute("token", accessToken);
//System.out.println("GoogleCallback accessToken=" + accessToken);
String requestUrl = "https://www.googleapis.com/oauth2/v1/userinfo";
final OAuthRequest oAuthrequest = new OAuthRequest(Verb.GET, requestUrl);
service.signRequest(accessToken, oAuthrequest);
final Response OAuthResponse = service.execute(oAuthrequest);
//fetch the gmail from google response
JSONObject bodyJsonObject = new JSONObject(OAuthResponse.getBody());
//System.out.println(bodyJsonObject.get("email").toString());
String gmail = bodyJsonObject.get("email").toString();
//A partir de l' email reconnu par google retrouver les informations locale
//li'e a cet email et faire le login
try {
/* pour le test ceci dans tomcat-users.xml
<user username="[email protected]" password="unsecretDansLeCodeSeulement" roles="user"/>
<user username="[email protected]" password="unsecretDansLeCodeSeulement" roles="admin,user"/>
<user username="[email protected]" password="unsecretDansLeCodeSeulement" roles="admin"/>
<user username="[email protected]" password="unsecretDansLeCodeSeulement" roles="user"/>
<user username="[email protected]" password="unsecretDansLeCodeSeulement" roles="user"/>
*/
request.login(gmail, "unsecretDansLeCodeSeulement");
User aUser = new User(gmail);
aUser.setData(String.format("<pre>%s</pre>", bodyJsonObject.toString(4)));
session.setAttribute("user", aUser);
response.sendRedirect(request.getContextPath());
} catch (ServletException ex) {
Logger.getLogger(GcallBack.class.getName()).log(Level.SEVERE, null, ex);
printToOutput(request, response, "Echec du login!");
}
} else {
printToOutput(request, response, "Pas de session servoice!");
}
} else {
printToOutput(request, response, "googleCode null");
}
}
示例10: executeRequest
import com.github.scribejava.core.oauth.OAuth20Service; //导入方法依赖的package包/类
private static String executeRequest(String requestUrl, OAuth20Service scribe, OAuth2AccessToken accessToken) throws IOException, ExecutionException, InterruptedException {
OAuthRequest request = new OAuthRequest(Verb.GET, requestUrl);
scribe.signRequest(accessToken, request);
Response response = scribe.execute(request);
if (!response.isSuccessful()) {
throw unexpectedResponseCode(requestUrl, response);
}
return response.getBody();
}
示例11: main
import com.github.scribejava.core.oauth.OAuth20Service; //导入方法依赖的package包/类
public static void main (String ... args) {
// Replace these with your client id and secret
mySecrets = ResourceBundle.getBundle("facebookutil/secret");
final String clientId = mySecrets.getString("googleId");
final String clientSecret = mySecrets.getString("googleSecret");
final OAuth20Service service = new ServiceBuilder()
.apiKey(clientId)
.apiSecret(clientSecret)
.scope("https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.circles.write https://www.googleapis.com/auth/plus.circles.read https://www.googleapis.com/auth/plus.stream.write https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/plus.stream.read")
.callback("https://github.com/duke-compsci308-spring2016/voogasalad_GitDepends")
.build(GoogleApi20.instance());
Scanner in = new Scanner(System.in, "UTF-8");
System.out.println("=== " + NETWORK_NAME + "'s OAuth Workflow ===");
System.out.println();
// Obtain the Authorization URL
System.out.println("Fetching the Authorization URL...");
final Map<String, String> additionalParams = new HashMap<>();
additionalParams.put("access_type", "offline");
// force to retrieve refresh token (if users are asked not the first time)
additionalParams.put("prompt", "consent");
final String authorizationUrl = service.getAuthorizationUrl(additionalParams);
System.out.println("Got the Authorization URL!");
System.out.println("Now go and authorize ScribeJava here:");
System.out.println(authorizationUrl);
System.out.println("And paste the authorization code here");
System.out.print(">>");
final String code = in.nextLine();
System.out.println();
System.out.println("Trading the Request Token for an Access Token...");
OAuth2AccessToken accessToken = service.getAccessToken(code);
System.out.println("Got the Access Token!");
System.out.println("(if your curious it looks like this: " + accessToken +
", 'rawResponse'='" + accessToken.getRawResponse() + "')");
System.out.println("Refreshing the Access Token...");
accessToken = service.refreshAccessToken(accessToken.getRefreshToken());
System.out.println("Refreshed the Access Token!");
System.out.println("(if your curious it looks like this: " + accessToken +
", 'rawResponse'='" + accessToken.getRawResponse() + "')");
System.out.println();
// Now let's go and ask for a protected resource!
System.out.println("Now we're going to access a protected resource...");
while (true) {
System.out
.println("Paste fieldnames to fetch (leave empty to get profile, 'exit' to stop example)");
System.out.print(">>");
final String query = in.nextLine();
System.out.println();
final String requestUrl;
if ("exit".equals(query)) {
break;
}
else if (query == null || query.isEmpty()) {
requestUrl = PROTECTED_RESOURCE_URL;
}
else {
requestUrl = PROTECTED_RESOURCE_URL + "?fields=" + query;
}
final OAuthRequest request = new OAuthRequest(Verb.GET, requestUrl, service);
service.signRequest(accessToken, request);
final Response response = request.send();
System.out.println();
System.out.println(response.getCode());
System.out.println(response.getBody());
System.out.println();
}
in.close();
}
示例12: callback
import com.github.scribejava.core.oauth.OAuth20Service; //导入方法依赖的package包/类
@RequestMapping("/callback")
public Object callback(
HttpServletRequest request,
HttpServletResponse response,
@RequestParam(required = false) String error,
@RequestParam String code,
@RequestParam("state") String stateStr
) throws InterruptedException, ExecutionException, IOException
{
if (error != null)
{
logger.info("Error in oauth callback: {}", error);
return null;
}
State state = gson.fromJson(stateStr, State.class);
logger.info("Got authorization code {} for uuid {}", code, state.getUuid());
OAuth20Service service = new ServiceBuilder()
.apiKey(oauthClientId)
.apiSecret(oauthClientSecret)
.scope(SCOPE)
.callback(RL_OAUTH_URL)
.state(gson.toJson(state))
.build(GoogleApi20.instance());
OAuth2AccessToken accessToken = service.getAccessToken(code);
// Access user info
OAuthRequest orequest = new OAuthRequest(Verb.GET, USERINFO);
service.signRequest(accessToken, orequest);
Response oresponse = service.execute(orequest);
if (oresponse.getCode() / 100 != 2)
{
// Could be a forged result
return null;
}
UserInfo userInfo = gson.fromJson(oresponse.getBody(), UserInfo.class);
logger.info("Got user info: {}", userInfo);
try (Connection con = sql2o.open())
{
con.createQuery("insert ignore into users (username) values (:username)")
.addParameter("username", userInfo.getEmail())
.executeUpdate();
UserEntry user = con.createQuery("select id from users where username = :username")
.addParameter("username", userInfo.getEmail())
.executeAndFetchFirst(UserEntry.class);
if (user == null)
{
logger.warn("Unable to find newly created user session");
return null; // that's weird
}
// insert session
con.createQuery("insert ignore into sessions (user, uuid) values (:user, :uuid)")
.addParameter("user", user.getId())
.addParameter("uuid", state.getUuid().toString())
.executeUpdate();
logger.info("Created session for user {}", userInfo.getEmail());
}
response.sendRedirect(RL_REDIR);
notifySession(state.getUuid(), userInfo.getEmail());
return "";
}
示例13: getResourceResponse
import com.github.scribejava.core.oauth.OAuth20Service; //导入方法依赖的package包/类
/**
* Executes an OAuth20 request
*
* @param oAuth20Service The service to access
* @param oAuth2AccessToken The access token to be used
* @param resource The resource URL to access
*
* @return A OAuth response
* @throws IOException
* @throws ExecutionException
* @throws InterruptedException
*/
private com.github.scribejava.core.model.Response getResourceResponse(OAuth20Service oAuth20Service, OAuth2AccessToken oAuth2AccessToken, String resource) throws InterruptedException, ExecutionException, IOException {
final OAuthRequest request = new OAuthRequest(Verb.GET, resource);
oAuth20Service.signRequest(oAuth2AccessToken, request);
return oAuth20Service.execute(request);
}