当前位置: 首页>>代码示例>>Java>>正文


Java OAuth20Service.getAccessToken方法代码示例

本文整理汇总了Java中com.github.scribejava.core.oauth.OAuth20Service.getAccessToken方法的典型用法代码示例。如果您正苦于以下问题:Java OAuth20Service.getAccessToken方法的具体用法?Java OAuth20Service.getAccessToken怎么用?Java OAuth20Service.getAccessToken使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在com.github.scribejava.core.oauth.OAuth20Service的用法示例。


在下文中一共展示了OAuth20Service.getAccessToken方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: 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) {
	}
}
 
开发者ID:AdeptJ,项目名称:adeptj-modules,代码行数:19,代码来源:OAuth2CallbackServlet.java

示例2: 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();
}
 
开发者ID:steven-turner,项目名称:sonar-auth-google,代码行数:31,代码来源:GoogleIdentityProvider.java

示例3: 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");
    }
}
 
开发者ID:ljug,项目名称:java-tutorials,代码行数:64,代码来源:GcallBack.java

示例4: onCallback

import com.github.scribejava.core.oauth.OAuth20Service; //导入方法依赖的package包/类
private void onCallback(CallbackContext context) throws InterruptedException, ExecutionException, IOException {
  context.verifyCsrfState();

  HttpServletRequest request = context.getRequest();
  OAuth20Service scribe = newScribeBuilder(context).build(scribeApi);
  String code = request.getParameter("code");
  OAuth2AccessToken accessToken = scribe.getAccessToken(code);

  GsonUser user = getUser(scribe, accessToken);
  if (isUnauthorized(accessToken, user.getLogin())) {
    throw new UnauthorizedException(format("'%s' must be a member of at least one organization: '%s'",
      user.getLogin(), Arrays.stream(settings.organizations()).collect(Collectors.joining("', '"))));
  }

  final String email;
  if (user.getEmail() == null) {
    // if the user has not specified a public email address in their profile
    email = getEmail(scribe, accessToken);
  } else {
    email = user.getEmail();
  }

  UserIdentity userIdentity = userIdentityFactory.create(user, email,
    settings.syncGroups() ? getTeams(scribe, accessToken) : null);
  context.authenticate(userIdentity);
  context.redirectToRequestedPage();
}
 
开发者ID:SonarSource,项目名称:sonar-auth-github,代码行数:28,代码来源:GitHubIdentityProvider.java

示例5: 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();
}
 
开发者ID:tomrom95,项目名称:GameAuthoringEnvironment,代码行数:77,代码来源:GooglePlusExample.java

示例6: 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 "";
}
 
开发者ID:runelite,项目名称:runelite,代码行数:77,代码来源:AccountService.java

示例7: main

import com.github.scribejava.core.oauth.OAuth20Service; //导入方法依赖的package包/类
public static void main(String... args) throws IOException {
    // Replace these with your client id and secret
    final String clientId = "your client id";
    final String clientSecret = "your client secret";

    final OAuth20Service service = new ServiceBuilder()
            .apiKey(clientId)
            .apiSecret(clientSecret)
            .scope("activity%20profile") // replace with desired scope
            .callback("http://example.com")  //your callback URL to store and handle the authorization code sent by Fitbit
            .state("some_params")
            .build(FitbitApi20.instance());
    final Scanner in = new Scanner(System.in);

    System.out.println("=== " + NETWORK_NAME + "'s OAuth Workflow ===");
    System.out.println();

    // Obtain the Authorization URL
    System.out.println("Fetching the Authorization URL...");
    final String authorizationUrl = service.getAuthorizationUrl();
    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();

    // Trade the Request Token and Verfier for the Access Token
    System.out.println("Trading the Request Token for an Access Token...");
    final 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();

    // Now let's go and ask for a protected resource!
    // This will get the profile for this user
    System.out.println("Now we're going to access a protected resource...");

    final OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL, service);
    request.addHeader("x-li-format", "json");

    //add header for authentication (why make it so complicated, Fitbit?)
    request.addHeader("Authorization", "Bearer " + accessToken.getAccessToken());

    final Response response = request.send();
    System.out.println();
    System.out.println(response.getCode());
    System.out.println(response.getBody());

    System.out.println();
}
 
开发者ID:alexthered,项目名称:fitbitAPI20-scribe-java,代码行数:54,代码来源:FitbitApi20Example.java


注:本文中的com.github.scribejava.core.oauth.OAuth20Service.getAccessToken方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。