Authenticating with a Service Account

Prerequisites

This page assumes that you have already:

Configuring authentication

To authenticate with a service account:

  1. Add the following to your @Api or method annotation:

    • Add an authenticators param to your annotation, set to the value {EspAuthenticator.class}.
    • Add an issuers param containing an @ApiIssuer.
    • Add an issuerAudiences param containing an @ApiIssuerAudience set to the service account issuer and your audience.

    For example:

    @Api(
        name = "echo",
        version = "v1",
        authenticators = {EspAuthenticator.class},
        issuers = {
            @ApiIssuer(
                name = "serviceAccount",
                issuer = "YOUR-SERVICE-ACCOUNT-EMAIL",
                jwksUri = "https://www.googleapis.com/robot/v1/metadata/x509/YOUR-SERVICE-ACCOUNT-EMAIL")
        },
        issuerAudiences = {
            @ApiIssuerAudience(name = "serviceAccount", audiences = "YOUR-AUDIENCE")
        })
    

    Replace echo with the name of your API, and replace v1 with your API version. Also replace YOUR-SERVICE-ACCOUNT-EMAIL with your service account email and YOUR-AUDIENCE with your audience. If you are using default service account credentials, set YOUR-AUDIENCE to https://www.googleapis.com/oauth2/v4/token. Otherwise, set it to the aud field sent by your client. See Using a Google ID token for details on generating a token for a service account.

  2. In your API implementation code, import Users:

    import com.google.api.server.spi.auth.common.User;
    
  3. In each API method where you want to check for proper authentication, check for a valid User and throw an exception if there isn't one, as shown in this sample method definition:

    @ApiMethod(httpMethod = ApiMethod.HttpMethod.GET)
    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;
    }
    
  4. Deploy the API. You need to redeploy the API whenever you add new clients.

Was this page helpful? Let us know how we did:

Send feedback about...

Cloud Endpoints Frameworks for App Engine
Need help? Visit our support page.