com.google.api.server.spi.auth.common.User Java Examples

The following examples show how to use com.google.api.server.spi.auth.common.User. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GoogleAppEngineAuthenticatorTest.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthenticateOAuth2CookieAuthBothFail() throws ServiceUnavailableException {
  authenticator = new GoogleAppEngineAuthenticator(oauthService, userService) {
    @Override
    com.google.appengine.api.users.User getOAuth2User(HttpServletRequest request,
        ApiMethodConfig config) {
      return null;
    }

    @Override
    boolean shouldTryCookieAuth(ApiMethodConfig config) {
      return true;
    }
  };
  when(userService.getCurrentUser()).thenReturn(null);
  assertNull(authenticator.authenticate(request));
}
 
Example #2
Source File: Echo.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the authenticated user's email. If the user is not authenticated, this will return an HTTP
 * 401.
 *
 * <p>Note that name is not specified. This will default to "{class name}.{method name}". For
 * example, the default is "echo.getUserEmail".
 *
 * <p>Note that httpMethod is not required here. Without httpMethod, this will default to GET due
 * to the API method name. httpMethod is added here for example purposes.
 */
// [START firebase_auth]
@ApiMethod(
    path = "firebase_user",
    httpMethod = ApiMethod.HttpMethod.GET,
    authenticators = {EspAuthenticator.class},
    issuerAudiences = {
        @ApiIssuerAudience(
            name = "firebase",
            audiences = {"YOUR-PROJECT-ID"}
        )
    }
)
public Email getUserEmailFirebase(User user) throws UnauthorizedException {
  if (user == null) {
    throw new UnauthorizedException("Invalid credentials");
  }

  Email response = new Email();
  response.setEmail(user.getEmail());
  return response;
}
 
Example #3
Source File: Echo.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the authenticated user's email. If the user is not authenticated, this will return an HTTP
 * 401.
 *
 * <p>Note that name is not specified. This will default to "{class name}.{method name}". For
 * example, the default is "echo.getUserEmail".
 *
 * <p>Note that httpMethod is not required here. Without httpMethod, this will default to GET due
 * to the API method name. httpMethod is added here for example purposes.
 */
// [START google_id_token_auth]
@ApiMethod(
    httpMethod = ApiMethod.HttpMethod.GET,
    authenticators = {EspAuthenticator.class},
    audiences = {"YOUR_OAUTH_CLIENT_ID"},
    clientIds = {"YOUR_OAUTH_CLIENT_ID"}
)
public Email getUserEmail(User user) throws UnauthorizedException {
  if (user == null) {
    throw new UnauthorizedException("Invalid credentials");
  }

  Email response = new Email();
  response.setEmail(user.getEmail());
  return response;
}
 
Example #4
Source File: Echo.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the authenticated user's email. If the user is not authenticated, this will return an HTTP
 * 401.
 *
 * Note that name is not specified. This will default to "{class name}.{method name}". For
 * example, the default is "echo.getUserEmail".
 *
 * Note that httpMethod is not required here. Without httpMethod, this will default to GET due
 * to the API method name. httpMethod is added here for example purposes.
 */
@ApiMethod(
    path = "firebase_user",
    httpMethod = ApiMethod.HttpMethod.GET,
    authenticators = {EspAuthenticator.class},
    issuerAudiences = {@ApiIssuerAudience(name = "firebase", audiences = {"YOUR-PROJECT-ID"})}
    )
public Email getUserEmailFirebase(User user) throws UnauthorizedException {
  if (user == null) {
    throw new UnauthorizedException("Invalid credentials");
  }

  Email response = new Email();
  response.setEmail(user.getEmail());
  return response;
}
 
Example #5
Source File: Echo.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the authenticated user's email. If the user is not authenticated, this will return an HTTP
 * 401.
 *
 * Note that name is not specified. This will default to "{class name}.{method name}". For
 * example, the default is "echo.getUserEmail".
 *
 * Note that httpMethod is not required here. Without httpMethod, this will default to GET due
 * to the API method name. httpMethod is added here for example purposes.
 */
@ApiMethod(
    httpMethod = ApiMethod.HttpMethod.GET,
    authenticators = {EspAuthenticator.class},
    audiences = {"YOUR_OAUTH_CLIENT_ID"},
    clientIds = {"YOUR_OAUTH_CLIENT_ID"}
    )
public Email getUserEmail(User user) throws UnauthorizedException {
  if (user == null) {
    throw new UnauthorizedException("Invalid credentials");
  }

  Email response = new Email();
  response.setEmail(user.getEmail());
  return response;
}
 
Example #6
Source File: TechGalleryAuthenticator.java    From tech-gallery with Apache License 2.0 6 votes vote down vote up
@Override
public User authenticate(HttpServletRequest req) {
    OAuthService authService = OAuthServiceFactory.getOAuthService();
    com.google.appengine.api.users.User currentUser;

    try {
      currentUser = authService.getCurrentUser(Constants.EMAIL_SCOPE);
      // Check current user..
      if(currentUser != null) {
        String email = currentUser.getEmail();
        // Check domain..
        if(isValidDomain(email) || isWhiteList(email)) {
          return new User(currentUser.getUserId(), currentUser.getEmail());
        }
      }
      throw new RestrictedDomainException(i18n.t("Authorization error"));
    }
    catch(OAuthRequestException  e) {
      log.log(Level.WARNING, "Error when trying to authenticate. Message: " + e.getMessage(), e);
      return null;
    }
}
 
Example #7
Source File: Auth.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
/**
 * Authenticate the request and retrieve an {@code com.google.appengine.api.users.User}. Should
 * only run once per request.
 */
com.google.appengine.api.users.User authenticateAppEngineUser() throws ServiceException {
  if (!EnvUtil.isRunningOnAppEngine()) {
    return null;
  }
  attr.set(Attribute.REQUIRE_APPENGINE_USER, true);
  User user = authenticate();
  attr.set(Attribute.REQUIRE_APPENGINE_USER, false);
  if (user == null) {
    return null;
  }
  com.google.appengine.api.users.User appEngineUser =
      attr.get(Attribute.AUTHENTICATED_APPENGINE_USER);
  if (appEngineUser != null) {
    return appEngineUser;
  } else {
    return user.getEmail() == null
        ? null : new com.google.appengine.api.users.User(user.getEmail(), "", user.getId());
  }
}
 
Example #8
Source File: GoogleAppEngineAuthenticatorTest.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthenticateOAuth2Fail() throws ServiceUnavailableException {
  authenticator = new GoogleAppEngineAuthenticator(oauthService, userService) {
    @Override
    com.google.appengine.api.users.User getOAuth2User(HttpServletRequest request,
        ApiMethodConfig config) {
      return null;
    }

    @Override
    boolean shouldTryCookieAuth(ApiMethodConfig config) {
      return false;
    }
  };
  assertNull(authenticator.authenticate(request));
}
 
Example #9
Source File: ServletRequestParamReaderTest.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
private Object[] readParameters(final String input, EndpointMethod method,
    ApiMethodConfig methodConfig, final User user,
    final com.google.appengine.api.users.User appEngineUser)
    throws Exception {
  ParamReader reader = new ServletRequestParamReader(method, endpointsContext, context, null,
      methodConfig) {
    @Override
    User getUser() {
      return user;
    }
    @Override
    com.google.appengine.api.users.User getAppEngineUser() {
      return appEngineUser;
    }
  };
  return readParameters(input, reader);
}
 
Example #10
Source File: ServletRequestParamReaderTest.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppEngineUserInjectionThrowsExceptionIfRequired() throws Exception {
  @SuppressWarnings("unused")
  class TestUser {
    @SuppressWarnings("unused")
    public void getUser(com.google.appengine.api.users.User user) { }
  }
  ApiMethodConfig methodConfig = Mockito.mock(ApiMethodConfig.class);
  when(methodConfig.getAuthLevel()).thenReturn(AuthLevel.REQUIRED);
  methodConfig.setAuthLevel(AuthLevel.REQUIRED);
  try {
    Method method = TestUser.class
        .getDeclaredMethod("getUser", com.google.appengine.api.users.User.class);
    readParameters(
        "{}",
        EndpointMethod.create(method.getDeclaringClass(), method),
        methodConfig,
        null,
        null);
    fail("expected unauthorized method exception");
  } catch (UnauthorizedException ex) {
    // expected
  }
}
 
Example #11
Source File: ServletRequestParamReaderTest.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testUserInjectionThrowsExceptionIfRequired() throws Exception {
  @SuppressWarnings("unused")
  class TestUser {
    @SuppressWarnings("unused")
    public void getUser(User user) { }
  }
  ApiMethodConfig methodConfig = Mockito.mock(ApiMethodConfig.class);
  when(methodConfig.getAuthLevel()).thenReturn(AuthLevel.REQUIRED);
  methodConfig.setAuthLevel(AuthLevel.REQUIRED);
  try {
    Method method = TestUser.class.getDeclaredMethod("getUser", User.class);
    readParameters(
        "{}", EndpointMethod.create(method.getDeclaringClass(), method),
        methodConfig,
        null,
        null);
    fail("expected unauthorized method exception");
  } catch (UnauthorizedException ex) {
    // expected
  }
}
 
Example #12
Source File: GoogleAppEngineAuthenticatorTest.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthenticateOAuth2FailCookieAuth() throws ServiceUnavailableException {
  authenticator = new GoogleAppEngineAuthenticator(oauthService, userService) {
    @Override
    com.google.appengine.api.users.User getOAuth2User(HttpServletRequest request,
        ApiMethodConfig config) {
      return null;
    }

    @Override
    boolean shouldTryCookieAuth(ApiMethodConfig config) {
      return true;
    }
  };
  when(userService.getCurrentUser()).thenReturn(APP_ENGINE_USER);
  assertEquals(USER, authenticator.authenticate(request));
  assertEquals(APP_ENGINE_USER, attr.get(Attribute.AUTHENTICATED_APPENGINE_USER));
}
 
Example #13
Source File: GoogleOAuth2AuthenticatorTest.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthenticate() throws ServiceUnavailableException {
  when(config.getScopeExpression()).thenReturn(AuthScopeExpressions.interpret("scope1"));
  when(config.getClientIds()).thenReturn(ImmutableList.of(CLIENT_ID));
  User user = authenticator.authenticate(request);
  assertEquals(EMAIL, user.getEmail());
  assertEquals(USER_ID, user.getId());
  final TokenInfo tokenInfo = attr.get(Attribute.TOKEN_INFO);
  assertNotNull(tokenInfo);
  assertEquals(EMAIL, tokenInfo.email);
  assertEquals(USER_ID, tokenInfo.userId);
}
 
Example #14
Source File: GoogleJwtAuthenticatorTest.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthenticate_skipClientIdCheck() throws Exception {
  request.removeAttribute(Attribute.ENABLE_CLIENT_ID_WHITELIST);
  when(verifier.verify(TOKEN)).thenReturn(token);
  when(config.getClientIds()).thenReturn(ImmutableList.of("clientId2"));
  when(config.getAudiences()).thenReturn(ImmutableList.of(AUDIENCE));
  User user = authenticator.authenticate(request);
  assertEquals(EMAIL, user.getEmail());
  assertEquals(USER_ID, user.getId());
  assertNotNull(attr.get(Attribute.ID_TOKEN));
}
 
Example #15
Source File: GoogleJwtAuthenticatorTest.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthenticate() throws Exception {
  when(verifier.verify(TOKEN)).thenReturn(token);
  when(config.getClientIds()).thenReturn(ImmutableList.of(CLIENT_ID));
  when(config.getAudiences()).thenReturn(ImmutableList.of(AUDIENCE));
  User user = authenticator.authenticate(request);
  assertEquals(EMAIL, user.getEmail());
  assertEquals(USER_ID, user.getId());
  GoogleIdToken idToken = attr.get(Attribute.ID_TOKEN);
  assertNotNull(idToken);
  assertEquals(EMAIL, idToken.getPayload().getEmail());
  assertEquals(USER_ID, idToken.getPayload().getSubject());
}
 
Example #16
Source File: GoogleJwtAuthenticatorTest.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthenticate_appEngineUser() throws GeneralSecurityException, IOException {
  attr.set(Attribute.REQUIRE_APPENGINE_USER, true);
  when(verifier.verify(TOKEN)).thenReturn(token);
  when(config.getClientIds()).thenReturn(ImmutableList.of(CLIENT_ID));
  when(config.getAudiences()).thenReturn(ImmutableList.of(AUDIENCE));
  User user = authenticator.authenticate(request);
  assertEquals(EMAIL, user.getEmail());
  assertEquals(USER_ID, user.getId());
  com.google.appengine.api.users.User appEngineuser =
      attr.get(Attribute.AUTHENTICATED_APPENGINE_USER);
  assertEquals(EMAIL, appEngineuser.getEmail());
  assertNull(appEngineuser.getUserId());
}
 
Example #17
Source File: GoogleOAuth2AuthenticatorTest.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthenticate_skipClientIdCheck() throws ServiceUnavailableException {
  request.removeAttribute(Attribute.ENABLE_CLIENT_ID_WHITELIST);
  when(config.getScopeExpression()).thenReturn(AuthScopeExpressions.interpret("scope1"));
  when(config.getClientIds()).thenReturn(ImmutableList.of("clientId2"));
  User user = authenticator.authenticate(request);
  assertEquals(EMAIL, user.getEmail());
  assertEquals(USER_ID, user.getId());
  assertNotNull(attr.get(Attribute.TOKEN_INFO));
}
 
Example #18
Source File: YourFirstAPI.java    From appengine-endpoints-helloworld-java-maven with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
// [START lookmeup]
/** A simple endpoint method that takes a name and says Hi back */
@ApiMethod(
    name = "lookmeup",
    httpMethod = ApiMethod.HttpMethod.GET)
public MyBean lookMeUp( User user)
    throws OAuthRequestException, RequestTimeoutException, NotFoundException, IOException {
  MyBean response = new MyBean();

  // Look me up here...
  // response = lookup(user);
  //

  if (response != null) {
    // [START notfound]
    throw new NotFoundException(user.getEmail());
    // [END notfound]
  }
  if (true /* did we time out */ ) {
    // [START timeout]
    throw new RequestTimeoutException("lookMeUp() timed out");  // custom timeout exception
    // [END timeout]
  }

  return response;
}
 
Example #19
Source File: GoogleOAuth2AuthenticatorTest.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthenticate_appEngineUser() throws ServiceUnavailableException {
  attr.set(Attribute.REQUIRE_APPENGINE_USER, true);
  when(config.getScopeExpression()).thenReturn(AuthScopeExpressions.interpret("scope1"));
  when(config.getClientIds()).thenReturn(ImmutableList.of(CLIENT_ID));
  User user = authenticator.authenticate(request);
  assertEquals(EMAIL, user.getEmail());
  assertEquals(USER_ID, user.getId());
  com.google.appengine.api.users.User appEngineuser =
      (com.google.appengine.api.users.User) attr.get(Attribute.AUTHENTICATED_APPENGINE_USER);
  assertEquals(EMAIL, appEngineuser.getEmail());
  assertNull(appEngineuser.getUserId());
}
 
Example #20
Source File: ApiConfigValidatorTest.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidateAuthenticator_noNullary() throws Exception {
  final class InvalidAuthenticator implements Authenticator {
    @SuppressWarnings("unused")
    public InvalidAuthenticator(int x) {}

    @SuppressWarnings("unused")
    @Override
    public User authenticate(HttpServletRequest request) {
      return null;
    }
  }

  config.getApiClassConfig().getMethods()
      .get(methodToEndpointMethod(TestEndpoint.class.getMethod("getResultNoParams")))
      .setAuthenticators(
          ImmutableList.<Class<? extends Authenticator>>of(InvalidAuthenticator.class));

  try {
    validator.validate(config);
    fail();
  } catch (InvalidConstructorException expected) {
    assertTrue(expected.getMessage().contains("Invalid custom authenticator"));
    assertTrue(expected.getMessage().endsWith(
        "InvalidAuthenticator. It must have a public nullary constructor."));
  }
}
 
Example #21
Source File: ApiConfigValidatorTest.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidateAuthenticator_privateNullary() throws Exception {
  final class InvalidAuthenticator implements Authenticator {
    @SuppressWarnings("unused")
    private InvalidAuthenticator() {}

    @SuppressWarnings("unused")
    @Override
    public User authenticate(HttpServletRequest request) {
      return null;
    }
  }

  config.getApiClassConfig().getMethods()
      .get(methodToEndpointMethod(TestEndpoint.class.getMethod("getResultNoParams")))
      .setAuthenticators(
          ImmutableList.<Class<? extends Authenticator>>of(InvalidAuthenticator.class));

  try {
    validator.validate(config);
    fail();
  } catch (InvalidConstructorException expected) {
    assertTrue(expected.getMessage().contains("Invalid custom authenticator"));
    assertTrue(expected.getMessage().endsWith(
        "InvalidAuthenticator. It must have a public nullary constructor."));
  }
}
 
Example #22
Source File: TestEndpoint.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
public Foo succeed(@Named(NAME_STRING) String s, @Named(NAME_BOOLEAN) boolean b1,
    @Named(NAME_INTEGER) int i1, @Named(NAME_LONG) long l1, @Named(NAME_FLOAT) float f1,
    @Named(NAME_DOUBLE) double d1, @Named(NAME_BOOLEAN_OBJECT) Boolean b2,
    @Named(NAME_INTEGER_OBJECT) Integer i2, @Named(NAME_LONG_OBJECT) Long l2,
    @Named(NAME_FLOAT_OBJECT) Float f2, @Named(NAME_DOUBLE_OBJECT) Double d2,
    Request request, User user1, com.google.appengine.api.users.User user2,
    HttpServletRequest servletRequest) {
  return RESULT;
}
 
Example #23
Source File: GoogleAppEngineAuthenticatorTest.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthenticateOAuth2() throws ServiceUnavailableException {
  authenticator = new GoogleAppEngineAuthenticator(oauthService, userService) {
    @Override
    com.google.appengine.api.users.User getOAuth2User(HttpServletRequest request,
        ApiMethodConfig config) {
      return APP_ENGINE_USER;
    }
  };
  assertEquals(USER, authenticator.authenticate(request));
  assertEquals(APP_ENGINE_USER, attr.get(Attribute.AUTHENTICATED_APPENGINE_USER));
}
 
Example #24
Source File: ServletRequestParamReaderTest.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
private Object[] readExecuteMethod(ImmutableMap<String, String> parameters) throws Exception {
  Method method = TestEndpoint.class.getDeclaredMethod("succeed", String.class,
      boolean.class, int.class, long.class, float.class, double.class,
      Boolean.class, Integer.class, Long.class, Float.class, Double.class,
      Request.class, User.class, com.google.appengine.api.users.User.class,
      HttpServletRequest.class);
  StringBuilder builder = new StringBuilder("{");
  for (Map.Entry<String, String> entry : parameters.entrySet()) {
    builder.append(String.format("\"%s\":%s,", entry.getKey(), entry.getValue()));
  }
  builder.replace(builder.length() - 1, builder.length(), "}");
  Object[] params = readParameters(builder.toString(), method);
  assertEquals(15, params.length);
  return params;
}
 
Example #25
Source File: EndpointsAuthenticator.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@Override
public User authenticate(HttpServletRequest request) throws ServiceUnavailableException {
  Attribute attr = Attribute.from(request);
  User user = jwtAuthenticator.authenticate(request);
  if (user == null) {
    if (EnvUtil.isRunningOnAppEngine() && attr.isEnabled(Attribute.REQUIRE_APPENGINE_USER)) {
      user = appEngineAuthenticator.authenticate(request);
    } else {
      user = oauth2Authenticator.authenticate(request);
    }
  }
  return user;
}
 
Example #26
Source File: GoogleAppEngineAuthenticator.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@Override
public User authenticate(HttpServletRequest request) throws ServiceUnavailableException {
  Attribute attr = Attribute.from(request);
  if (!EnvUtil.isRunningOnAppEngine()) {
    return null;
  }

  com.google.appengine.api.users.User appEngineUser = null;
  ApiMethodConfig config = attr.get(Attribute.API_METHOD_CONFIG);
  if (!attr.isEnabled(Attribute.SKIP_TOKEN_AUTH)) {
    appEngineUser = getOAuth2User(request, config);
  }
  if (appEngineUser == null && shouldTryCookieAuth(config)) {
    appEngineUser = userService.getCurrentUser();
  }
  if (appEngineUser == null) {
    return null;
  }
  User user = new User(appEngineUser.getEmail());
  if (attr.isEnabled(Attribute.REQUIRE_APPENGINE_USER)) {
    logger.atInfo().log("appEngineUser = %s", appEngineUser);
    attr.set(Attribute.AUTHENTICATED_APPENGINE_USER, appEngineUser);
  } else {
    logger.atInfo().log("User = %s", user);
  }
  return user;
}
 
Example #27
Source File: Auth.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
/**
 * Authenticate the request and retrieve a {@code User}. Should only run once per request.
 */
User authenticate() throws ServiceException {
  Iterable<Authenticator> authenticators = getAuthenticatorInstances();
  User user = null;
  if (authenticators != null) {
    for (Authenticator authenticator : authenticators) {
      user = authenticator.authenticate(request);
      if (user != null) {
        break;
      }
    }
  }
  return user;
}
 
Example #28
Source File: GoogleOAuth2Authenticator.java    From endpoints-java with Apache License 2.0 4 votes vote down vote up
@Override
public User authenticate(HttpServletRequest request) throws ServiceUnavailableException {
  Attribute attr = Attribute.from(request);
  if (attr.isEnabled(Attribute.SKIP_TOKEN_AUTH)) {
    return null;
  }

  String token = GoogleAuth.getAuthToken(request);
  if (!GoogleAuth.isOAuth2Token(token)) {
    return null;
  }

  GoogleAuth.TokenInfo tokenInfo = getTokenInfoRemote(token);
  if (tokenInfo == null) {
    return null;
  }

  attr.set(Attribute.TOKEN_INFO, tokenInfo);

  ApiMethodConfig config = (ApiMethodConfig) request.getAttribute(Attribute.API_METHOD_CONFIG);

  // Check scopes.
  if (Strings.isEmptyOrWhitespace(tokenInfo.scopes)) {
    logger.atWarning().log("Access token does not contain a valid scope");
    return null;
  }
  String[] authorizedScopes = tokenInfo.scopes.split("\\s+");
  if (!config.getScopeExpression().isAuthorized(ImmutableSet.copyOf(authorizedScopes))) {
    logger.atWarning().log(
        "Access token does not contain sufficient scopes from: %s", config.getScopeExpression());
    return null;
  }

  // Check clientId.
  if (attr.isEnabled(Attribute.ENABLE_CLIENT_ID_WHITELIST)
      && !GoogleAuth.checkClientId(tokenInfo.clientId, config.getClientIds(), true)) {
    logger.atWarning().log("ClientId is not allowed: %s", tokenInfo.clientId);
    return null;
  }

  User user = new User(tokenInfo.userId, tokenInfo.email);
  if (attr.isEnabled(Attribute.REQUIRE_APPENGINE_USER)) {
    com.google.appengine.api.users.User appEngineUser =
        new com.google.appengine.api.users.User(tokenInfo.email, "");
    logger.atInfo().log("appEngineUser = %s", appEngineUser);
    request.setAttribute(Attribute.AUTHENTICATED_APPENGINE_USER, appEngineUser);
  } else {
    logger.atInfo().log("user = %s", user);
  }
  return user;
}
 
Example #29
Source File: GoogleJwtAuthenticator.java    From endpoints-java with Apache License 2.0 4 votes vote down vote up
@Override
public User authenticate(HttpServletRequest request) {
  Attribute attr = Attribute.from(request);
  if (attr.isEnabled(Attribute.SKIP_TOKEN_AUTH)) {
    return null;
  }

  String token = GoogleAuth.getAuthToken(request);
  if (!GoogleAuth.isJwt(token)) {
    return null;
  }

  GoogleIdToken idToken = verifyToken(token);
  if (idToken == null) {
    return null;
  }

  attr.set(Attribute.ID_TOKEN, idToken);

  String clientId = idToken.getPayload().getAuthorizedParty();
  String audience = (String) idToken.getPayload().getAudience();

  ApiMethodConfig config = attr.get(Attribute.API_METHOD_CONFIG);

  // Check client id.
  if ((attr.isEnabled(Attribute.ENABLE_CLIENT_ID_WHITELIST)
      && !GoogleAuth.checkClientId(clientId, config.getClientIds(), false))) {
    logger.atWarning().log("ClientId is not allowed: %s", clientId);
    return null;
  }
  // Check audience.
  if (!GoogleAuth.checkAudience(audience, config.getAudiences(), clientId)) {
    logger.atWarning().log("Audience is not allowed: %s", audience);
    return null;
  }

  String userId = idToken.getPayload().getSubject();
  String email = idToken.getPayload().getEmail();
  User user = (userId == null && email == null) ? null : new User(userId, email);
  if (attr.isEnabled(Attribute.REQUIRE_APPENGINE_USER)) {
    com.google.appengine.api.users.User appEngineUser =
        (email == null) ? null : new com.google.appengine.api.users.User(email, "");
    attr.set(Attribute.AUTHENTICATED_APPENGINE_USER, appEngineUser);
    logger.atFine().log("appEngineUser = %s", appEngineUser);
  } else {
    logger.atFine().log("user = %s", user);
  }
  return user;
}
 
Example #30
Source File: ServletRequestParamReader.java    From endpoints-java with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
com.google.appengine.api.users.User getAppEngineUser() throws ServiceException {
  return Auth.from(endpointsContext.getRequest()).authenticateAppEngineUser();
}