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


Java AppIdentityService类代码示例

本文整理汇总了Java中com.google.appengine.api.appidentity.AppIdentityService的典型用法代码示例。如果您正苦于以下问题:Java AppIdentityService类的具体用法?Java AppIdentityService怎么用?Java AppIdentityService使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


AppIdentityService类属于com.google.appengine.api.appidentity包,在下文中一共展示了AppIdentityService类的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: sign

import com.google.appengine.api.appidentity.AppIdentityService; //导入依赖的package包/类
private byte[] sign(byte[] data) {
    byte[] signature;
    if (Environment.is(Environment.DEV)) {
        try {
            Signature rsa = Signature.getInstance("SHA256withRSA");
            rsa.initSign(gcsCredential.getServiceAccountPrivateKey());
            rsa.update(data);
            signature = rsa.sign();
        } catch (Exception e) {
            throw new GoogleCloudStorageException(e, "Error signing URL: %s", e.getMessage());
        }
    } else {
        AppIdentityService.SigningResult signingResult = appIdentityService.signForApp(data);
        signature = signingResult.getSignature();
    }
    return signature;
}
 
开发者ID:3wks,项目名称:generator-thundr-gae-react,代码行数:18,代码来源:GoogleCloudStorageJsonApiClient.java

示例2: createFirebaseToken

import com.google.appengine.api.appidentity.AppIdentityService; //导入依赖的package包/类
/**
 * Create a secure JWT token for the given userId.
 */
public String createFirebaseToken(Game game, String userId) {
  final AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
  final BaseEncoding base64 = BaseEncoding.base64();

  String header = base64.encode("{\"typ\":\"JWT\",\"alg\":\"RS256\"}".getBytes());

  // Construct the claim
  String channelKey = game.getChannelKey(userId);
  String clientEmail = appIdentity.getServiceAccountName();
  long epochTime = System.currentTimeMillis() / 1000;
  long expire = epochTime + 60 * 60; // an hour from now

  Map<String, Object> claims = new HashMap<String, Object>();
  claims.put("iss", clientEmail);
  claims.put("sub", clientEmail);
  claims.put("aud", IDENTITY_ENDPOINT);
  claims.put("uid", channelKey);
  claims.put("iat", epochTime);
  claims.put("exp", expire);

  String payload = base64.encode(new Gson().toJson(claims).getBytes());
  String toSign = String.format("%s.%s", header, payload);
  AppIdentityService.SigningResult result = appIdentity.signForApp(toSign.getBytes());
  return String.format("%s.%s", toSign, base64.encode(result.getSignature()));
}
 
开发者ID:GoogleCloudPlatform,项目名称:java-docs-samples,代码行数:29,代码来源:FirebaseChannel.java

示例3: testGetAccessTokenWithScope

import com.google.appengine.api.appidentity.AppIdentityService; //导入依赖的package包/类
@Test
public void testGetAccessTokenWithScope() {
    Date beforeRequest = new Date();
    List<String> scopes = new ArrayList<>();
    scopes.add("https://www.googleapis.com/auth/urlshortener");
    AppIdentityService.GetAccessTokenResult tokenResult = appIdentity.getAccessToken(scopes);

    Assert.assertNotNull(tokenResult);
    Assert.assertTrue("Token should not be blank.", !tokenResult.getAccessToken().isEmpty());

    String errMsg = "Expiration time should at least be after request time. " +
        dateDebugStr("Before-Request", beforeRequest) + ", " + dateDebugStr("Expiration-Time=", tokenResult.getExpirationTime());
    Assert.assertTrue(errMsg, beforeRequest.getTime() < tokenResult.getExpirationTime().getTime());
    log.info("AccessToken: " + tokenResult.getAccessToken() +
        " Expiration: " + tokenResult.getExpirationTime());

    // Retrieve it again, should be same since it grabs it from a cache.
    AppIdentityService.GetAccessTokenResult tokenResult2 = appIdentity.getAccessToken(scopes);

    Assert.assertEquals(tokenResult.getAccessToken(), tokenResult2.getAccessToken());
}
 
开发者ID:GoogleCloudPlatform,项目名称:appengine-tck,代码行数:22,代码来源:AppIdentityServiceTest.java

示例4: testGetAccessTokenUncached

import com.google.appengine.api.appidentity.AppIdentityService; //导入依赖的package包/类
@Test
public void testGetAccessTokenUncached() {
    Date beforeRequest = new Date();
    List<String> scopes = new ArrayList<>();
    scopes.add("https://www.googleapis.com/auth/urlshortener");

    // Although we do not verify whether the result came from the cache or not,
    // the token should at least be valid.
    AppIdentityService.GetAccessTokenResult tokenResult = appIdentity.getAccessTokenUncached(scopes);

    Assert.assertNotNull(tokenResult);
    Assert.assertTrue("Token should not be blank.", !tokenResult.getAccessToken().isEmpty());

    String errMsg = "Expiration time should at least be after request time. " +
        dateDebugStr("Before-Request", beforeRequest) + ", " + dateDebugStr("Expiration-Time=", tokenResult.getExpirationTime());
    Assert.assertTrue(errMsg, beforeRequest.getTime() < tokenResult.getExpirationTime().getTime());
    log.info("AccessToken: " + tokenResult.getAccessToken() +
        " Expiration: " + tokenResult.getExpirationTime());
}
 
开发者ID:GoogleCloudPlatform,项目名称:appengine-tck,代码行数:20,代码来源:AppIdentityServiceTest.java

示例5: testSignForApp

import com.google.appengine.api.appidentity.AppIdentityService; //导入依赖的package包/类
@Test
/**
 * Verify that all certificates returned will validate signForApp().  Any invalid signature or
 * exception will cause the test to fail.
 */
public void testSignForApp() throws Exception {
    Collection<PublicCertificate> certs = appIdentity.getPublicCertificatesForApp();
    byte[] blob = "abcdefg".getBytes();
    AppIdentityService.SigningResult result = appIdentity.signForApp(blob);
    byte[] signedBlob = result.getSignature();
    boolean res = verifySignatureWithAllCertsForApp(blob, signedBlob, certs);

    // assertTrue(res) returns null, so using assertEquals()
    Assert.assertEquals("signature.verify() returned false. See logs.", true, res);
    Assert.assertTrue(!result.getKeyName().isEmpty());
}
 
开发者ID:GoogleCloudPlatform,项目名称:appengine-tck,代码行数:17,代码来源:AppIdentityServiceTest.java

示例6: GoogleCloudStorageJsonApiClient

import com.google.appengine.api.appidentity.AppIdentityService; //导入依赖的package包/类
public GoogleCloudStorageJsonApiClient(HttpRequestFactory httpRequestFactory,
    AppIdentityService appIdentityService,
    GoogleCredential gcsCredential) {
    this.httpRequestFactory = httpRequestFactory;
    this.appIdentityService = appIdentityService;
    this.gcsCredential = gcsCredential;
}
 
开发者ID:3wks,项目名称:generator-thundr-gae-react,代码行数:8,代码来源:GoogleCloudStorageJsonApiClient.java

示例7: createShortUrl

import com.google.appengine.api.appidentity.AppIdentityService; //导入依赖的package包/类
/**
 * Returns a shortened URL by calling the Google URL Shortener API.
 *
 * <p>Note: Error handling elided for simplicity.
 */
public String createShortUrl(String longUrl) throws Exception {
  ArrayList<String> scopes = new ArrayList<String>();
  scopes.add("https://www.googleapis.com/auth/urlshortener");
  final AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
  final AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(scopes);
  // The token asserts the identity reported by appIdentity.getServiceAccountName()
  JSONObject request = new JSONObject();
  request.put("longUrl", longUrl);

  URL url = new URL("https://www.googleapis.com/urlshortener/v1/url?pp=1");
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setDoOutput(true);
  connection.setRequestMethod("POST");
  connection.addRequestProperty("Content-Type", "application/json");
  connection.addRequestProperty("Authorization", "Bearer " + accessToken.getAccessToken());

  OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
  request.write(writer);
  writer.close();

  if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
    // Note: Should check the content-encoding.
    //       Any JSON parser can be used; this one is used for illustrative purposes.
    JSONTokener responseTokens = new JSONTokener(connection.getInputStream());
    JSONObject response = new JSONObject(responseTokens);
    return (String) response.get("id");
  } else {
    try (InputStream s = connection.getErrorStream();
        InputStreamReader r = new InputStreamReader(s, StandardCharsets.UTF_8)) {
      throw new RuntimeException(String.format(
          "got error (%d) response %s from %s",
          connection.getResponseCode(),
          CharStreams.toString(r),
          connection.toString()));
    }
  }
}
 
开发者ID:GoogleCloudPlatform,项目名称:java-docs-samples,代码行数:43,代码来源:UrlShortener.java

示例8: createShortUrl

import com.google.appengine.api.appidentity.AppIdentityService; //导入依赖的package包/类
/**
 * Returns a shortened URL by calling the Google URL Shortener API.
 *
 * <p>Note: Error handling elided for simplicity.
 */
public String createShortUrl(String longUrl) throws Exception {
  ArrayList<String> scopes = new ArrayList<String>();
  scopes.add("https://www.googleapis.com/auth/urlshortener");
  final AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
  final AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(scopes);
  // The token asserts the identity reported by appIdentity.getServiceAccountName()
  JSONObject request = new JSONObject();
  request.put("longUrl", longUrl);

  URL url = new URL("https://www.googleapis.com/urlshortener/v1/url?pp=1");
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setDoOutput(true);
  connection.setRequestMethod("POST");
  connection.addRequestProperty("Content-Type", "application/json");
  connection.addRequestProperty("Authorization", "Bearer " + accessToken.getAccessToken());

  OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
  request.write(writer);
  writer.close();

  if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
    // Note: Should check the content-encoding.
    //       Any JSON parser can be used; this one is used for illustrative purposes.
    JSONTokener responseTokens = new JSONTokener(connection.getInputStream());
    JSONObject response = new JSONObject(responseTokens);
    return (String) response.get("id");
  } else {
    try (InputStream s = connection.getErrorStream();
        InputStreamReader r = new InputStreamReader(s, StandardCharsets.UTF_8)) {
      throw new RuntimeException(
          String.format(
              "got error (%d) response %s from %s",
              connection.getResponseCode(), CharStreams.toString(r), connection.toString()));
    }
  }
}
 
开发者ID:GoogleCloudPlatform,项目名称:java-docs-samples,代码行数:42,代码来源:UrlShortener.java

示例9: getProjectId

import com.google.appengine.api.appidentity.AppIdentityService; //导入依赖的package包/类
/**
 * Returns the project ID.
 *
 * @return the project ID.
 */
public static String getProjectId() {
    AppIdentityService identityService =
            AppIdentityServiceFactory.getAppIdentityService();

    // The project ID associated to an app engine application is the same
    // as the app ID.
    return identityService.parseFullAppId(ApiProxy.getCurrentEnvironment()
            .getAppId()).getId();
}
 
开发者ID:GoogleCloudPlatform,项目名称:cloud-pubsub-samples-java,代码行数:15,代码来源:PubsubUtils.java

示例10: testParseFullAppId

import com.google.appengine.api.appidentity.AppIdentityService; //导入依赖的package包/类
@Test
public void testParseFullAppId() {
    // [(partition)~][(domain):](display-app-id)
    ApiProxy.Environment env = ApiProxy.getCurrentEnvironment();
    String hostname = (String) env.getAttributes().get("com.google.appengine.runtime.default_version_hostname");
    AppIdentityService.ParsedAppId parsed = appIdentity.parseFullAppId(hostname);

    String message = createParsed(parsed);
    Assert.assertEquals(message, property("testParseFullAppId_partition").getPropertyValue(), parsed.getPartition());
    Assert.assertEquals(message, getExpectedAppHostname("testParseFullAppId_domain"), parsed.getDomain());
    Assert.assertEquals(message, getExpectedAppId("testParseFullAppId_id"), parsed.getId());
}
 
开发者ID:GoogleCloudPlatform,项目名称:appengine-tck,代码行数:13,代码来源:AppIdentityServiceTest.java

示例11: CloudFileManager

import com.google.appengine.api.appidentity.AppIdentityService; //导入依赖的package包/类
public CloudFileManager() {
  AppIdentityService appIdentityService = AppIdentityServiceFactory.getAppIdentityService();
  defaultBucket = appIdentityService.getDefaultGcsBucketName();
  productionManifestFile = new GcsFilename(defaultBucket, Config.MANIFEST_NAME);
  stagingManifestFile = new GcsFilename(defaultBucket, Config.MANIFEST_NAME_STAGING);
}
 
开发者ID:dreaminglion,项目名称:iosched-reader,代码行数:7,代码来源:CloudFileManager.java

示例12: signBlob

import com.google.appengine.api.appidentity.AppIdentityService; //导入依赖的package包/类
private byte[] signBlob(byte[] blob) {
  AppIdentityService.SigningResult result = appIdentity.signForApp(blob);
  return result.getSignature();
}
 
开发者ID:GoogleCloudPlatform,项目名称:java-docs-samples,代码行数:5,代码来源:SignForAppServlet.java

示例13: createParsed

import com.google.appengine.api.appidentity.AppIdentityService; //导入依赖的package包/类
private String createParsed(AppIdentityService.ParsedAppId parsed) {
    return parsed.getDomain() + " : " + parsed.getId() + " : " + parsed.getPartition();
}
 
开发者ID:GoogleCloudPlatform,项目名称:appengine-tck,代码行数:4,代码来源:AppIdentityServiceTest.java

示例14: getAccessToken

import com.google.appengine.api.appidentity.AppIdentityService; //导入依赖的package包/类
/**
 * Get the access token for a list of scopes.
 *
 * @param scopes the scopes to get the access tokens for.
 * @return the access token.
 */
public static String getAccessToken(List<String> scopes) {
  final AppIdentityService appIdService = AppIdentityServiceFactory.getAppIdentityService();
  AppIdentityService.GetAccessTokenResult result = appIdService.getAccessToken(scopes);
  return result.getAccessToken();
}
 
开发者ID:GoogleCloudPlatform,项目名称:solutions-google-compute-engine-orchestrator,代码行数:12,代码来源:GceApiUtils.java


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