## Prerequisites

This page assumes that you have already:

- [Created a Google Cloud project](https://docs.cloud.google.com/resource-manager/docs/creating-managing-projects.md.txt).

- [Added API management](https://docs.cloud.google.com/endpoints/docs/frameworks/java/adding-api-management.md.txt).

## Configuring authentication

To authenticate with a service account:

1. Add the following to your
   [`@Api`](https://docs.cloud.google.com/endpoints/docs/frameworks/java/annotations.md.txt#api_api-scoped_annotations)
   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`:

   ```java
   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:

   ```java
   @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](https://docs.cloud.google.com/endpoints/docs/frameworks/java/test-deploy.md.txt). You need to
   redeploy the API whenever you add new clients.