Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Cette page explique comment permettre l'authentification des utilisateurs dans votre API à partir d'applications clientes utilisant Cloud Endpoints Frameworks. Sachez que les clients Android et JavaScript sont actuellement compatibles.
Cloud Endpoints Frameworks accepte l'authentification des utilisateurs à partir d'applications clientes utilisant l'une des méthodologies suivantes :
Quelle que soit la méthode d'authentification employée, dans chaque méthode d'API pour laquelle vous souhaitez confirmer que l'authentification est appropriée, vous devez rechercher un élément User valide, comme décrit dans les sections suivantes :
Procéder à l'authentification via la fonctionnalité d'authentification de Firebase
Pour pouvoir gérer les appels de clients utilisant l'authentification Firebase :
Si vous ne l'avez pas déjà fait, créez un projet Firebase. Les projets Firebase sont des projets de la console Google Cloud qui utilisent les services Firebase. Pour en savoir plus, consultez la page Qu'est-ce qu'un projet Firebase ? ainsi que la documentation Firebase.
Ajoutez les éléments suivants à votre annotation de méthode ou @Api :
Ajoutez à l'annotation un paramètre authenticators défini sur la valeur {EspAuthenticator.class}.
Ajoutez un paramètre issuers contenant un élément @ApiIssuer défini sur Firebase.
Ajoutez un paramètre issuerAudiences contenant un élément @ApiIssuerAudience défini sur Firebase et l'ID du projet.
Remplacez VERSION_NUMBER par la version de votre API, par exemple, v1.
Remplacez les deux instances de YOUR_PROJECT_ID par l'ID du projet Firebase.
Dans le code de mise en œuvre de l'API, importez Users :
importcom.google.api.server.spi.auth.common.User;
Dans chaque méthode API pour laquelle vous souhaitez vérifier que l'authentification est appropriée, recherchez un élément User valide. S'il n'y en a pas, générez une exception comme indiqué dans cet exemple de définition de méthode :
Vous pouvez ajouter l'authentification Firebase à votre code comme décrit dans la documentation Firebase. Le client doit être associé à un projet Google Cloud , et l'ID du projet doit être répertorié dans la configuration d'émetteur Firebase de l'API, comme indiqué dans la section précédente.
Procéder à l'authentification via Auth0
Pour pouvoir gérer les appels de clients utilisant Auth0 :
Ajoutez les éléments suivants à votre annotation de méthode ou @Api :
Ajoutez à l'annotation un paramètre authenticators défini sur la valeur {EspAuthenticator.class}.
Ajoutez un paramètre issuers contenant un élément @ApiIssuer défini sur Auth0.
Ajoutez un paramètre issuerAudiences contenant un élément @ApiIssuerAudience défini sur Auth0 et l'ID client Auth0.
Remplacez VERSION_NUMBER par la version de votre API, par exemple, v1.
Remplacez YOUR_ACCOUNT_NAME par le nom de compte Auth0 utilisé pour le client.
Remplacez AUTH0_CLIENT_ID par l'ID que vous souhaitez utiliser pour votre client.
Dans le code de mise en œuvre de l'API, importez Users :
importcom.google.api.server.spi.auth.common.User;
Dans chaque méthode API pour laquelle vous souhaitez vérifier que l'authentification est appropriée, recherchez un élément User valide. S'il n'y en a pas, générez une exception comme indiqué dans cet exemple de définition de méthode :
Vous pouvez ajouter l'authentification Auth0 à votre code comme décrit dans la documentation Auth0. Le client doit être répertorié dans la configuration d'émetteur Auth0 de l'API.
Procéder à l'authentification via les jetons d'ID Google
Pour pouvoir gérer les appels de clients qui s'authentifient à l'aide de jetons d'ID Google :
Obtenez un ID client OAuth 2.0 pour chaque application cliente. Le propriétaire de l'application cliente doit générer l'ID client à partir de la console Google Cloud .
Pour obtenir des instructions, consultez la page Créer des ID client.
Ajoutez une entrée clientIds contenant l'ID client pour chaque application cliente à laquelle vous accordez l'accès, ainsi qu'une entrée audiences pour chaque client Android, dans votre annotation @Api.
Exemple :
@Api(
name = "YOUR_API_NAME",
version = "VERSION_NUMBER",
clientIds = {"YOUR_CLIENT_ID"},
audiences = {"YOUR_CLIENT_ID"}
)
Remplacez YOUR_API_NAME par le nom de votre API.
Remplacez VERSION_NUMBER par la version de votre API, par exemple, v1.
Remplacez YOUR_CLIENT_ID par l'ID client OAuth 2.0 généré dans le projet de l'application cliente.
Dans le code de mise en œuvre de l'API, importez Users :
importcom.google.api.server.spi.auth.common.User;
Dans chaque méthode API pour laquelle vous souhaitez vérifier que l'authentification est appropriée, recherchez un élément User valide. S'il n'y en a pas, générez une exception comme indiqué dans cet exemple de définition de méthode :
Si vous utilisez un jeton JWT dans le client pour envoyer des requêtes authentifiées à l'API, ce jeton doit figurer dans l'en-tête d'autorisation d'une requête HTTP. Il doit avoir les revendications requises suivantes :
iss
sub
aud
iat
exp
Étape suivante
Pour obtenir des informations générales sur l'authentification des utilisateurs et les différences avec l'autorisation via des clés API, consultez la page Quand et pourquoi utiliser les clés API.
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/09/04 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/09/04 (UTC)."],[[["\u003cp\u003eThis guide outlines how to enable user authentication in your API using Cloud Endpoints Frameworks, currently supporting Android and JavaScript clients.\u003c/p\u003e\n"],["\u003cp\u003eEndpoints Frameworks allows authentication via Firebase Auth, Auth0, or Google ID tokens, and each method requires checking for a valid \u003ccode\u003eUser\u003c/code\u003e in the API method.\u003c/p\u003e\n"],["\u003cp\u003eTo implement authentication, you must configure \u003ccode\u003e@Api\u003c/code\u003e or method annotations with appropriate \u003ccode\u003eauthenticators\u003c/code\u003e, \u003ccode\u003eissuers\u003c/code\u003e, and \u003ccode\u003eissuerAudiences\u003c/code\u003e parameters specific to your chosen authentication method (Firebase, Auth0, or Google ID).\u003c/p\u003e\n"],["\u003cp\u003eAPI methods must include a check for a valid \u003ccode\u003eUser\u003c/code\u003e, throwing an \u003ccode\u003eUnauthorizedException\u003c/code\u003e if the user is null, and you should redeploy your API after adding clients or changing any configurations.\u003c/p\u003e\n"],["\u003cp\u003eWhen using JWT in clients, the JWT should be included in the authorization header of HTTP requests and must contain \u003ccode\u003eiss\u003c/code\u003e, \u003ccode\u003esub\u003c/code\u003e, \u003ccode\u003eaud\u003c/code\u003e, \u003ccode\u003eiat\u003c/code\u003e, and \u003ccode\u003eexp\u003c/code\u003e claims.\u003c/p\u003e\n"]]],[],null,["# Authenticating users\n\nThis page describes how to add support in your API for user authentication from\nclient applications using Cloud Endpoints Frameworks. Note that\nAndroid and JavaScript clients are currently supported.\n\nEndpoints Frameworks supports user authentication from client\napplications that use any of the following methodologies:\n\n- [Firebase Auth](https://firebase.google.com/docs/auth/)\n- [Auth0](http://auth0.com)\n- [Google ID tokens](/endpoints/docs/frameworks/glossary#google_id_token)\n\nNo matter which authentication method you use, in each API method where you want\nto check for proper authentication, you must check for a valid `User` as\ndescribed in the following sections:\n\n- [Authenticating with Firebase Auth](#authenticating_with_firebase_auth)\n- [Authenticating with Auth0](#authenticating_with_auth0)\n- [Authenticating with Google ID tokens](#google-id-tokens)\n\nPrerequisites\n-------------\n\nThis page assumes that you have already:\n\n- Created a [Google Cloud\n project](/resource-manager/docs/creating-managing-projects).\n\n- [Added API management](/endpoints/docs/frameworks/java/adding-api-management).\n\nAuthenticating with Firebase Auth\n---------------------------------\n\nTo support calls from clients that use Firebase Auth:\n\n1. If you haven't already done so, create a Firebase project. Firebase projects\n are Google Cloud console projects that use Firebase services. For more\n information, see\n [What is a Firebase project?](https://support.google.com/firebase/answer/6399760?hl=en)\n and the\n [Firebase documentation](https://firebase.google.com/docs/).\n\n2. Add the following to your\n [`@Api`](/endpoints/docs/frameworks/java/annotations#api_api-scoped_annotations)\n or method annotation:\n\n - Add an `authenticators` parameter to your annotation, set to the value `{EspAuthenticator.class}`.\n - Add an `issuers` parameter containing an `@ApiIssuer` set to Firebase.\n - Add an `issuerAudiences` parameter containing an `@ApiIssuerAudience` set to Firebase and your project ID.\n\n For example: \n\n ```\n @Api(\n name = \"YOUR_API_NAME\",\n version = \"VERSION_NUMBER\",\n authenticators = {EspAuthenticator.class},\n issuers = {\n @ApiIssuer(\n name = \"firebase\",\n issuer = \"https://securetoken.google.com/YOUR_PROJECT_ID\",\n jwksUri = \"https://www.googleapis.com/service_accounts/v1/metadata/x509/securetoken@system.gserviceaccount.com\")\n },\n issuerAudiences = {\n @ApiIssuerAudience(name = \"firebase\", audiences = \"YOUR_PROJECT_ID\")\n })\n ```\n - Replace \u003cvar translate=\"no\"\u003eYOUR_API_NAME\u003c/var\u003e with the name of your API.\n - Replace \u003cvar translate=\"no\"\u003eVERSION_NUMBER\u003c/var\u003e with your API version, for example, `v1`.\n - Replace both instances of \u003cvar translate=\"no\"\u003eYOUR_PROJECT_ID\u003c/var\u003e with your Firebase project ID.\n3. In your API implementation code, import `Users`:\n\n import com.google.api.server.spi.auth.common.User;\n\n4. In each API method where you want to check for proper authentication,\n check for a valid `User` and throw an exception if there isn't one, as\n shown in this sample method definition:\n\n @ApiMethod(httpMethod = ApiMethod.HttpMethod.GET)\n public Email getUserEmail(User user) throws UnauthorizedException {\n if (user == null) {\n throw new UnauthorizedException(\"Invalid credentials\");\n }\n\n Email response = new Email();\n response.setEmail(user.getEmail());\n return response;\n }\n\n5. [Redeploy the API](/endpoints/docs/frameworks/java/test-deploy)\n whenever you add new clients.\n\n### Adding Firebase authentication to a client\n\nYou can add Firebase authentication to your code as described in the\n[Firebase](https://firebase.google.com/docs/auth/)\ndocumentation. The client must have a Google Cloud project\nassociated with it, and the project ID must be listed in the API's Firebase\nissuer configuration as shown in the preceding section.\n\nAuthenticating with Auth0\n-------------------------\n\nTo support calls from clients that use Auth0:\n\n1. Add the following to your\n [`@Api`](/endpoints/docs/frameworks/java/annotations#api_api-scoped_annotations)\n or method annotation:\n\n - Add an `authenticators` parameter to your annotation, set to the value `{EspAuthenticator.class}`.\n - Add an `issuers` parameter containing an `@ApiIssuer` set to Auth0.\n - Add an `issuerAudiences` parameter containing an `@ApiIssuerAudience` set to Auth0 and your Auth0 client ID.\n\n For example: \n\n ```\n @Api(\n name = \"YOUR_API_NAME\",\n version = \"VERSION_NUMBER\",\n authenticators = {EspAuthenticator.class},\n issuers = {\n @ApiIssuer(\n name = \"auth0\",\n issuer = \"https://YOUR_ACCOUNT_NAME.auth0.com/\",\n jwksUri = \"https://YOUR_ACCOUNT_NAME.auth0.com/.well-known/jwks.json\")\n },\n issuerAudiences = {\n @ApiIssuerAudience(name = \"auth0\", audiences = \"AUTH0_CLIENT_ID\")\n })\n ```\n - Replace \u003cvar translate=\"no\"\u003eYOUR_API_NAME\u003c/var\u003e with the name of your API.\n - Replace \u003cvar translate=\"no\"\u003eVERSION_NUMBER\u003c/var\u003e with your API version, for example, `v1`.\n - Replace \u003cvar translate=\"no\"\u003eYOUR_ACCOUNT_NAME\u003c/var\u003e with the Auth0 account name used for the client.\n - Replace \u003cvar translate=\"no\"\u003eAUTH0_CLIENT_ID\u003c/var\u003e with the ID you want to use for your client.\n2. In your API implementation code, import `Users`:\n\n import com.google.api.server.spi.auth.common.User;\n\n3. In each API method where you want to check for proper authentication,\n check for a valid `User` and throw an exception if there isn't one, as\n shown in this sample method definition:\n\n @ApiMethod(httpMethod = ApiMethod.HttpMethod.GET)\n public Email getUserEmail(User user) throws UnauthorizedException {\n if (user == null) {\n throw new UnauthorizedException(\"Invalid credentials\");\n }\n\n Email response = new Email();\n response.setEmail(user.getEmail());\n return response;\n }\n\n4. [Redeploy the API](/endpoints/docs/frameworks/java/test-deploy)\n whenever you add new clients.\n\n### Adding Auth0 authentication to a client\n\nYou can add Auth0 authentication to your code as described in the\n[Auth0](http://auth0.com)\ndocumentation. The client must be listed in the API's Auth0 issuer\nconfiguration.\n\nAuthenticating with Google ID tokens\n------------------------------------\n\nTo support calls from clients that authenticate using Google ID tokens:\n\n1. Obtain an OAuth 2 client ID for each client application. The client\n application owner must generate the client ID from the Google Cloud console.\n For instructions, see\n [Creating client IDs](/endpoints/docs/frameworks/java/creating-client-ids).\n\n2. Add a `clientIds` entry containing the client ID for each client app\n you are granting access to, and an `audiences` entry as well for each\n Android client, in your\n [`@Api` annotation](/endpoints/docs/frameworks/java/annotations#api_api-scoped_annotations).\n\n For example: \n\n ```\n @Api(\n name = \"YOUR_API_NAME\",\n version = \"VERSION_NUMBER\",\n clientIds = {\"YOUR_CLIENT_ID\"},\n audiences = {\"YOUR_CLIENT_ID\"}\n )\n ```\n - Replace \u003cvar translate=\"no\"\u003eYOUR_API_NAME\u003c/var\u003e with the name of your API.\n - Replace \u003cvar translate=\"no\"\u003eVERSION_NUMBER\u003c/var\u003e with your API version, for example, `v1`.\n - Replace \u003cvar translate=\"no\"\u003eYOUR_CLIENT_ID\u003c/var\u003e with the OAuth 2 client ID that was generated in the client application project.\n3. In your API implementation code, import `Users`:\n\n import com.google.api.server.spi.auth.common.User;\n\n4. In each API method where you want to check for proper authentication, check\n for a valid `User` and throw an exception if there isn't one, as\n shown in this sample method definition:\n\n @ApiMethod(httpMethod = ApiMethod.HttpMethod.GET)\n public Email getUserEmail(User user) throws UnauthorizedException {\n if (user == null) {\n throw new UnauthorizedException(\"Invalid credentials\");\n }\n\n Email response = new Email();\n response.setEmail(user.getEmail());\n return response;\n }\n\n5. [Redeploy the API](/endpoints/docs/frameworks/java/test-deploy)\n whenever you add new clients.\n\n### Adding Google ID tokens authentication to a client\n\nFor information on adding authentication code to clients, see the following:\n\n- [Android app](/endpoints/docs/frameworks/java/calling-from-android)\n\nSending a JWT in your client\n----------------------------\n\nIf you use a JWT in your client to send authenticated requests to the API, the\nJWT must be in the authorization header of a HTTP request. The JWT should have\nthe following required claims:\n\n- `iss`\n- `sub`\n- `aud`\n- `iat`\n- `exp`\n\nWhat's next\n-----------\n\nFor background information about user authentication and how it differs from\nAPI key authorization, see\n[When and why to use API keys](/endpoints/docs/frameworks/java/when-why-api-key)."]]