Granulare OAuth-Berechtigungen für Google Chat-Apps verwalten

Chat-Apps, die die Nutzerauthentifizierung verwenden, müssen detaillierte OAuth-Berechtigungen unterstützen, damit Nutzer nur einen Teil der angeforderten Bereiche gewähren können. Ein Nutzer kann beispielsweise den Zugriff auf seinen Namen gewähren, den Zugriff auf seinen Kalender aber ablehnen.

Der Umgang mit detaillierten OAuth-Berechtigungen hängt davon ab, wie Sie Ihre Chat-App erstellen:

Apps Script

Wenn Sie Ihre Chat-App mit Apps Script erstellen, werden die detaillierten OAuth-Berechtigungen automatisch verarbeitet. Achten Sie jedoch darauf, dass Ihr Code Fälle abdeckt, in denen ein Nutzer nicht alle angeforderten Bereiche gewährt. Folgen Sie der Anleitung unter Granulare OAuth-Berechtigungen in Apps Script verarbeiten.

HTTP-Endpunkte

Wenn Sie Ihre Chat-App mit HTTP-Endpunkten erstellen, konfigurieren Sie Ihren Code so, dass er detaillierte OAuth-Berechtigungen verarbeitet. Prüfen Sie, welche Autorisierungsbereiche der Nutzer gewährt hat, und fordern Sie bei Bedarf die Autorisierung für fehlende oder alle Bereiche an.

  1. Geben Sie in der Manifestdatei Ihrer Chat-App die erforderlichen Autorisierungsbereiche im Feld oauthScopes an. Dieses Feld ist Teil der Ressource projects.deployments.

    Für das folgende Beispiel sind die Autorisierungsbereiche chat.messages und calendar.events erforderlich:

    JSON

    {
      "oauthScopes": [
        "https://www.googleapis.com/auth/chat.messages",
        "https://www.googleapis.com/auth/calendar.events"
      ],
      "addOns": {
        "common": {
          "name": "My Chat App",
          "logoUrl": "https://lh3.googleusercontent.com/..."
        },
        "chat": {},
        "calendar": {},
        "httpOptions": {}
      }
    }
    
  2. Im Feld authorizationEventObject.authorizedScopes sehen Sie, welche Bereiche der Nutzer gewährt hat. Wenn ein erforderlicher Bereich fehlt, geben Sie die Aktion requesting_google_scopes zurück, um den Nutzer nach den fehlenden Bereichen zu fragen.

    Node.js

    // Check for authorized scopes.
    const authorizedScopes = req.body.authorizationEventObject?.authorizedScopes || [];
    if (!authorizedScopes.includes('https://www.googleapis.com/auth/chat.messages')) {
      // Respond with a request for the missing scope.
      res.send({
        'requesting_google_scopes': {
          'scopes': ['https://www.googleapis.com/auth/chat.messages']
        }
      });
      return;
    }
    

    Python

    from flask import jsonify, request
    
    # Check for authorized scopes.
    event_data = request.get_json()
    authorized_scopes = event_data.get('authorizationEventObject', {}).get('authorizedScopes', [])
    if 'https://www.googleapis.com/auth/chat.messages' not in authorized_scopes:
        # Respond with a request for the missing scope.
        return jsonify({
            'requesting_google_scopes': {
                'scopes': ['https://www.googleapis.com/auth/chat.messages']
            }
        })
    

    Java

    import com.google.gson.JsonArray;
    import com.google.gson.JsonObject;
    import java.util.List;
    
    // Check for authorized scopes.
    List<String> authorizedScopes = event.getAuthorizationEventObject() != null
        ? event.getAuthorizationEventObject().getAuthorizedScopes()
        : null;
    if (authorizedScopes == null || !authorizedScopes.contains("https://www.googleapis.com/auth/chat.messages")) {
      // Respond with a request for the missing scope.
      JsonObject requestingGoogleScopes = new JsonObject();
      JsonArray scopes = new JsonArray();
      scopes.add("https://www.googleapis.com/auth/chat.messages");
      requestingGoogleScopes.add("scopes", scopes);
    
      JsonObject response = new JsonObject();
      response.add("requesting_google_scopes", requestingGoogleScopes);
      return response.toString();
    }
    

    Wenn Sie alle mit der Chat-App verknüpften Bereiche anfordern möchten, setzen Sie all_scopes auf true:

    Node.js

    res.send({
      'requesting_google_scopes': { 'all_scopes': true }
    });
    

    Python

    from flask import jsonify
    
    return jsonify({
        'requesting_google_scopes': { 'all_scopes': True }
    })
    

    Java

    import com.google.gson.JsonObject;
    
    JsonObject requestingGoogleScopes = new JsonObject();
    requestingGoogleScopes.addProperty("all_scopes", true);
    
    JsonObject response = new JsonObject();
    response.add("requesting_google_scopes", requestingGoogleScopes);
    return response.toString();
    

Eine ausführliche Anleitung finden Sie unter Detaillierte Berechtigungen für HTTP-Google Workspace-Add-ons verwalten.

Chat-Apps, die keine Add-ons sind: Detaillierte OAuth-Berechtigungen für Google Chat-Apps verwalten

Wenn Sie eine Chat-App verwalten, die kein Google Workspace-Add‑on ist, folgen Sie der Anleitung unten, um detaillierte OAuth-Berechtigungen zu verwalten.

Apps Script-Chat-Apps, die keine Add‑ons sind

Wenn Sie eine Chat-App, die kein Add‑on ist, mit Apps Script erstellt haben, gilt die Anleitung unter Granulare OAuth-Berechtigungen in Apps Script verarbeiten mit einer Einschränkung:

ScriptApp.requireScopes beendet die Scriptausführung, wenn die angegebenen Bereiche nicht gewährt werden. Der Nutzer sieht in Chat jedoch eine Konfigurationskarte anstelle des OAuth-Zustimmungsbildschirms. Auf der Konfigurationskarte wird der Nutzer immer aufgefordert, alle angeforderten Bereiche zu gewähren, nicht nur die, die noch nicht gewährt wurden.

Wenn Sie einzelne Prüfungen auf Autorisierungsbereichsebene durchführen möchten, verwenden Sie ScriptApp.getAuthorizationInfo, um die Autorisierung zu prüfen und bei Bedarf eine Autorisierung über eine private Nachricht anzufordern.

Das folgende Beispiel zeigt, wie Sie nach einer bestimmten Berechtigung (z. B. Kalenderzugriff) suchen und, falls sie fehlt, eine private Nachricht mit der erforderlichen Autorisierungs-URL zurückgeben.

Apps Script

/**
* Responds to a MESSAGE event in Google Chat.
* Checks for required permissions and if missing asks for them.
*
* @param {Object} event the event object from Chat
* @return {Object} JSON response
*/
function onMessage(event) {
  // Check if the script has the necessary permissions.
  // In this example, the script checks for the "calendar.events" scope.
  var requiredScopes = ['https://www.googleapis.com/auth/calendar.events'];
  var authInfo = ScriptApp.getAuthorizationInfo(ScriptApp.AuthMode.FULL, requiredScopes);

  // If permissions are missing, return a message with the authorization URL.
  if (authInfo.getAuthorizationStatus() === ScriptApp.AuthorizationStatus.REQUIRED) {
    var authUrl = authInfo.getAuthorizationUrl();
    return {
      "text": "This action requires authorization. Please <" + authUrl + "|click here to authorize>.",
      "privateMessageViewer": {
        "name": event.user.name
      }
    };
  }

  // Permission granted; proceed with the application logic.
  // ...
}

HTTP-Chat-Apps, die keine Add-ons sind

Wenn Ihre Chat-App, die kein Add-on ist, ein HTTP-Dienst ist, verwalten Sie den OAuth 2.0-Ablauf selbst.

Wenn Sie ein gespeichertes Token abrufen oder einen Autorisierungscode austauschen, prüfen Sie, welche Bereiche gewährt wurden. Wenn erforderliche Bereiche fehlen, fordern Sie den Nutzer auf, sie zu autorisieren.

Node.js

// 1. List authorized scopes.
const fs = require('fs');
const tokens = JSON.parse(fs.readFileSync('token.json'));
const grantedScopes = tokens.scope.split(' ');

// 2. Detect missing scopes.
const requiredScopes = ['https://www.googleapis.com/auth/chat.messages'];
const missingScopes = requiredScopes.filter(scope => !grantedScopes.includes(scope));

if (missingScopes.length > 0) {
  // 3. Request missing scopes.
  const authUrl = oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: missingScopes,
    include_granted_scopes: true
  });
  res.redirect(authUrl);
}

// To request all scopes instead of just the missing ones:
const allScopesAuthUrl = oauth2Client.generateAuthUrl({
  access_type: 'offline',
  scope: requiredScopes,
  include_granted_scopes: true
});

Python

from flask import redirect
from google.oauth2.credentials import Credentials

# 1. List authorized scopes.
credentials = Credentials.from_authorized_user_file('token.json')
granted_scopes = set(credentials.scopes)

# 2. Detect missing scopes.
required_scopes = {'https://www.googleapis.com/auth/chat.messages'}
missing_scopes = required_scopes - granted_scopes

if missing_scopes:
    # 3. Request missing scopes.
    flow.scope = list(missing_scopes)
    auth_url, _ = flow.authorization_url(
        access_type='offline',
        include_granted_scopes=True
    )
    return redirect(auth_url)

# To request all scopes instead of just the missing ones:
flow.scope = list(required_scopes)
all_scopes_auth_url, _ = flow.authorization_url(
    access_type='offline',
    include_granted_scopes='true'
)

Java

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

// 1. List authorized scopes.
// The "user" string is the user ID for which to load credentials.
Credential credential = flow.loadCredential("user");
Collection<String> grantedScopes = credential.getScopes();

// 2. Detect missing scopes.
// The `requiredScopes` variable contains a list of the OAuth scopes
// that your app requires to function. Define this variable with the
// scopes needed by your application.
List<String> requiredScopes = Arrays.asList("https://www.googleapis.com/auth/chat.messages");
List<String> missingScopes = new ArrayList<>();
for (String scope : requiredScopes) {
  if (!grantedScopes.contains(scope)) {
    missingScopes.add(scope);
  }
}

if (!missingScopes.isEmpty()) {
  // 3. Request missing scopes.
  GoogleAuthorizationCodeRequestUrl urlBuilder = new GoogleAuthorizationCodeRequestUrl(
      clientId, redirectUri, missingScopes)
      .setAccessType("offline")
      .set("include_granted_scopes", "true");
  String authUrl = urlBuilder.build();
  response.sendRedirect(authUrl);
}

// To request all scopes instead of just the missing ones:
GoogleAuthorizationCodeRequestUrl allScopesUrlBuilder = new GoogleAuthorizationCodeRequestUrl(
    clientId, redirectUri, requiredScopes)
    .setAccessType("offline")
    .set("include_granted_scopes", "true");
String allScopesAuthUrl = allScopesUrlBuilder.build();