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 parameter to your annotation, set to the value {EspAuthenticator.class}.
    • Add an issuers parameter containing an @ApiIssuer.
    • Add an issuerAudiences parameter 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.
    • Replace v1 with your API version.
    • Replace YOUR_SERVICE_ACCOUNT_EMAIL with your service account email.
    • Replace YOUR_AUDIENCE with the value in the aud field sent by the calling service.
  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.