Spezifikation der User API Keys

Discourse verfügt über ein System zur Erstellung von API-Schlüsseln pro Benutzer, wenn ein sehr spezifisches Protokoll befolgt wird. Diese Funktion ermöglicht den „Anwendungs“-Zugriff auf Discourse-Instanzen, ohne dass Moderatoren einbezogen werden müssen.

Überblick

Im Überblick:

  1. Client (Desktop-App, Browser-Plugin, mobile App) generiert ein privates/öffentliches Schlüsselpaar und eine Rückruf-URL
  2. Client leitet zu einer Route auf Discourse um und übergibt Discourse seinen öffentlichen Schlüssel
  3. Discourse holt die Zustimmung des Benutzers zur Verwendung der App ein
  4. Discourse generiert einen Benutzer-API-Schlüssel
  5. Discourse leitet mit einem verschlüsselten Payload unter Verwendung des öffentlichen API-Schlüssels, der den Benutzer-API-Schlüssel enthält, zur Rückruf-URL zurück

Details

Anwendungsfälle:

  1. Desktop-Anwendungen, die Discourse-Seiten im Auftrag von Endbenutzern abfragen, um Benachrichtigungszähler über mehrere Websites hinweg abzurufen.
  2. Mobile Anwendungen, die Discourse-Seiten im Auftrag von Endbenutzern abfragen und Push-Benachrichtigungen verarbeiten
  3. Webanwendungen, die ein Dashboard für Endbenutzer zu verschiedenen Discourse-Seiten bereitstellen.
  4. Benutzerdefinierte Integrationen mit Apps von Drittanbietern, die Discourse als Teil einer allgemeinen Unternehmens-App nutzen. Z. B. die Integration von Discourse-Community-Benachrichtigungen in die Hopscotch-App.

Das Design:

Website-Einstellungen

  • allow_user_api_key_scopes: Zulässige Zugriffsbereiche (Scopes) für Benutzer-API-Schlüssel. Die Scopes sind hier definiert. Die verfügbaren integrierten Scopes sind: read, write, message_bus, push, one_time_password, notifications, session_info, bookmarks_calendar, user_status (Plugins können zusätzliche Scopes registrieren).

  • user_api_key_allowed_groups: steuert, welche Gruppen Benutzer-API-Schlüssel generieren dürfen (standardmäßig Administratoren, Moderatoren und trust_level_0)

  • allowed_user_api_push_urls: Liste der Websites, die Ziele für Push-Benachrichtigungen sein können

  • allowed_user_api_auth_redirects: zulässige Weiterleitungsziele nach der Generierung des Benutzer-API-Schlüssels

Globale Einstellungen

  • max_user_api_reqs_per_minute: 20
  • max_user_api_reqs_per_day: 2880

UX-Elemente

Wenn Benutzer-API-Schlüssel erteilt wurden, zeigt Discourse einen Tab Apps auf der Benutzerseite an.

Der Tab Apps listet auf:

  • Der Name der Anwendung, z. B. („Discourse Notifier“)
  • Datum der letzten Nutzung
  • Genehmigungsdatum
  • Liste der gewährten Zugriffsbereiche
  • Eine Schaltfläche Zugriff widerrufen, damit Sie alle Schlüssel einfach widerrufen können

UI zur API-Schlüssel-Autorisierung

Jeder Schlüssel muss von den Endbenutzern auf einer Seite, die klar erklärt, was vor sich geht, explizit autorisiert werden, zum Beispiel:

„Discourse Notifier“ bittet um den folgenden Zugriff auf Ihr Konto:

  • Benachrichtigungen lesen und löschen
  • Benutzer-Sitzungsinformationen lesen
  • Ein einmaliges Anmeldetoken erstellen

[Autorisieren]

API-Schlüssel-Generierungsfluss

Die API erfordert vom Benutzer nur eine einzige GET-Anfrage.

https://sitename.com/user-api-key/new

:exclamation: Ab Discourse 2.1 laufen diese Benutzer-API-Schlüssel automatisch ab, wenn sie längere Zeit nicht verwendet werden. Die Website-Einstellung: revoke user api keys unused days ist standardmäßig auf 180 gesetzt

Parameter:

  • auth_redirect: URL, zu der mit dem generierten Token zurückgeleitet werden soll
  • application_name: der Name der anfragenden Anwendung (wird im Tab „Apps“ des Benutzerkontos angezeigt)
  • client_id: eine eindeutige Kennung für den Client
  • nonce: ein vom Client generierter eindeutiger Nonce. Dieser wird im verschlüsselten Payload zurückgegeben, damit der Client die Authentizität der Antwort überprüfen kann
  • scopes: kommaseparierte Liste der für den Schlüssel zulässigen Zugriffsbereiche, siehe allow user api key scopes für die vollständige Liste der verfügbaren Scopes
  • push_url: URL, an die Push-Benachrichtigungen gesendet werden sollen (erforderlich und nur gültig, wenn push oder notifications in den Scopes enthalten sind)
  • public_key: der öffentliche Teil des vom Client generierten Schlüsselpaars
  • padding (optional): der RSA-Padding-Modus, der zur Verschlüsselung des Payloads verwendet wird. Akzeptierte Werte sind pkcs1 (Standard) oder oaep. OAEP wird für neue Anwendungen empfohlen.

Nachdem /user-api-key/new mit den korrekten Parametern aufgerufen wurde, können 2 Dinge passieren:

  1. Wenn der Benutzer nicht angemeldet ist, werden wir zur Anmeldung weitergeleitet (nach der Anmeldung setzen wir die Autorisierung fort)
  2. Sobald ein Benutzer angemeldet ist, wird ihm die Autorisierungs-UI angezeigt.

Nachdem die Autorisierung erteilt wurde, leitet das System zu der in auth_redirect angegebenen URL zurück und fügt einen verschlüsselten payload-Parameter hinzu, der ein JSON-Objekt mit dem generierten Benutzer-API-Schlüssel (key), dem nonce, dem Push-Status (push) und der API-Version (api) enthält. Wenn der Scope one_time_password angefordert wurde, wird auch ein separater verschlüsselter oneTimePassword-Query-Parameter enthalten sein. client_id wird aus Sicherheitsgründen nicht zurückgegeben.

Überprüfung der API-Version

Die Verwendung des Schlüssel-APIs in Discourse ist versioniert. Clients können die API-Version einer Discourse-Site überprüfen, indem sie eine HEAD-Anfrage an https://sitename.com/user-api-key/new stellen. Die Antwort enthält einen Header namens Auth-Api-Version, der die Versionsnummer der API der Website enthält.

Nutzung der API

Die Nutzung der Client-API unterscheidet sich etwas von der aktuellen Admin-API.

Der Client kann 2 Header angeben:

User-Api-Key (erforderlich): der Schlüssel, der generiert wurde

und

User-Api-Client-Id (optional): diesen übergeben, um die in der Datenbank gespeicherte „Client-ID“ für diesen api_key zu aktualisieren.

Sobald diese Header angegeben sind, kann der Client Anfragen gegen die API so stellen, wie er es normalerweise tun würde.

Generieren eines Einmal-Anmelde-Passworts

Ab Version 4 enthält die API einen speziellen Scope: den Scope one_time_password, der es Clients ermöglicht, den Benutzer-API-Schlüssel zur Generierung eines Einmal-Passworts zu verwenden. Wenn der Client diesen Scope beim Generieren des API-Schlüssels gemäß den oben genannten Schritten einschließt, wird ein verschlüsseltes oneTimePassword als separater Query-Parameter in der Rückleitung an den Client aufgenommen.

Alternativ kann der Client eine GET-Anfrage an /user-api-key/otp mit den folgenden Parametern senden:

  • auth_redirect
  • application_name
  • public_key
  • padding (optional)

und mit dem Header User-Api-Key.

Diese Anfrage leitet zu einem Bildschirm in Discourse weiter, auf dem der Benutzer die Anwendung zur Genehmigung des Zugriffs auf die Website aufgefordert wird. Wenn der Benutzer zustimmt, leitet die Website zurück an die in auth_redirect definierte URL und enthält einen verschlüsselten oneTimePassword-Parameter mit einem Einmal-Passwort, das der Client verwenden kann, um sich auf der Website anzumelden, indem er https://sitename.com/session/otp/ONE-TIME-PASSWORD anfordert. (Das Einmal-Passwort ist nur 10 Minuten lang gültig.)

Widerrufen von API-Schlüsseln

Um einen API-Schlüssel zu widerrufen, senden Sie eine POST-Anfrage mit dem Header User-Api-Key und ohne Parameter an /user-api-key/revoke.


Zuletzt geprüft von @SaraDev am 2022-07-13T00:00:00Z

30 „Gefällt mir“
Generating User Api Keys with REST API
Discourse Login & Registeration
Discourse sso login using Rest API
Custom Push Notifications: allowed user api push urls
Beta testing the iOS mobile app
Can non-admin user issue their own API key?
How can I get user details via the user api key?
Authorization from a desktop application (and base domain site)
Secure way of encrypting payload in Javascript for user authentification
API CORS Headers Incorrect
Generating User Api Keys with REST API
Get back Username with API Key?
Automatic Login from iOS/Android app
Is there any documentation on the User/Mobile API?
Delegated authentication for Discourse Mobile app
Generating User Api Keys with REST API
Passing draft text into a new response
Discourse Hub "connect"
Generate User API Keys for testing
Consolidated API Requests in the thousands yet our site has no active API keys listed, is this a concern?
Having issue accessing the Discourse APIs from react app
Discourse REST API Documentation
Having issue accessing the Discourse APIs from react app
CORS error accessing API from javascript application
Does Discourse have support for PAT tokens?
API key creation
Access via Discourse API, key and/or user rejected
Feasibility of allowing a User Api Key client to register a valid auth_redirect
Implement discourse Apple login using API
Thousands of user api requests and invalidation
Are User API Keys Not Generated When Logging in via Login Link?
Confusion about API Authenticated User
Confusion about API Authenticated User
Generate User Api Key Without User Approval
How to use discourse api in react native?
How can I allow users to like posts using RESTapi
'Clip To Discourse' Chrome Extension
Dexo - A Native iOS Client for Discourse
'Clip To Discourse' Chrome Extension
"Api-Key" and "Api-Username" for try.discourse.org?
Unable to create "Single User" level API key, always defaults to "All Users"
Discourse index
Authentication Protocol re: App Integration
Embed Discourse in a native app?
Request header field User-Api-Key is not allowed by Access-Control-Allow-Headers
Request header field User-Api-Key is not allowed by Access-Control-Allow-Headers
Request header field Content-Type is not allowed by Access-Control-Allow-Headers
Improve BAD CSRF error message when making API calls with content-type application/json
Create apikey for user programmatically as admin
How to fix 'Cannot read property '_links' of undefined'
Acess-Control-Allow-Headers CORS Error with API after updating discourse
Allow API use by regular users, not just admins
The purpose of the 2 Discourse API systems
Bot writer's tip: Processing every post
Using Zapier without being admin
Per User API Keys Not Working
Acess-Control-Allow-Headers CORS Error with API after updating discourse
Work with discourse users on an SPA

There are places I’ve strongly considered writing a delayed post tool, so I can compose a bunch of “word of the day” type things to keep going while I’m on vacation. Doing it without proper API access and pretending to be a browser seems somewhat more complicated than on other forum software.

(Just as an example of another use case.)

That is a good example, but keep in mind, our default will be only to enable read tokens, not write ones. Site admins will have to opt to allow write tokens.

Completely agree that the _t cookie hacks are a huge problem.

2 „Gefällt mir“

Does max_user_api_calls_per_key_day setting apply to admin-created keys at /admin/api?

1 „Gefällt mir“

Nope only to user api keys, we can look at adding extra limits for standard Api keys, it is a good safeguard

1 „Gefällt mir“

To be clear, this is not implemented yet, correct?

No, it’s there (for almost 2,5 years now) - Admin - Settings - User API.

4 „Gefällt mir“

As of Discourse 2.1 these user api keys now auto-expire if left unused for long periods of time, correct @sam?

2 „Gefällt mir“

Correct the site setting: expire user api keys days is set to 180 out of the box.

2 „Gefällt mir“

Okay, but you have to have admin access to see that page yes? And as an admin, it seems I can only create 1 key, so can’t create many keys for different users. confused.

1 „Gefällt mir“

What are you trying to accomplish? It’s not clear because there is this (user api keys) and regular API tokens (which is what I think you are after) that admins can create for multiple users, but you have to do that from the individual user’s page inside of the admin dashboard by clicking on the “generate” button on the “API Key” field.

4 „Gefällt mir“

Thanks! Yes, “regular API tokens” for users is what i was after. I’m sure I’d seen that a million times, and never realized it was there. :heavy_check_mark:

3 „Gefällt mir“

Hey everyone I’m not sure if this was resolved? I see that it’s possible to create an “All Users” and (per user) level API token as an admin, but I’m interested in giving a user the power to generate his/her own token. Has there been work done on this? It sounds like the original thread was getting at this idea, and then it was lost. Thanks!

Download the mobile App and then add a site, that uses the user api key system you have to follow a very strict workflow, no plans to expose arbitrary generation of keys in user prefs

3 „Gefällt mir“

Thank you! I downloaded the app, and then realized that the sites I belong to don’t have this enabled (I’ve been testing on my local machine with the Dockerized discourse). Just to make sure we are talking about the same thing - I’m interested in generating tokens to use just a scoped subset of functions (and not global API keys to do all the things). Is this what you are talking about?

It seems like, given that there is an endpoint to generate tokens, it would be logical to provide this function (to users with a certain trust level, for example) from within the site. Otherwise, it would need to be the case that the site generates some external page (with a server to hide an admin token) to generate the keys for the user. Is it the case that 1. there is no internal generation of tokens for the user (and why not?) and 2. Nobody has created some external app (javascript, flask, anything really) to perform this action?

1 „Gefällt mir“

Yes.

Possibly, conceptually

  1. This is tricky to consume cause you need to use custom HTTP headers (by design)

  2. It would be very hard to educate even TL3 users about what the point is of this thing.

I prefer not to ship UI for this in core, but maybe you should write a plugin for your specific use case?

Can you explain a bit more about the “why” here?

The design of the system centers around “I have an external dedicated program”, “this program knows how to follow Discourse protocol”, “It asks for token”

API keys (non user ones) are much easier to consume cause you just append them after the ?

4 „Gefällt mir“

Can I pass the API key generated from the user page on this? I was trying to use that API key and seeing ‘You are not permitted to view the requested resource.’ error on /categories.json API request

Hi guys

Apologies if this is duplication but I am having trouble digesting the steps there even though they are very well put together

I have a discourse installation on https://forum.domain.com and a site on https://development.domain.com from which I need to make calls to the discourse installation to pull and set some data.

All requests work from postman with Api-Username and Api-Key - no problem

However for cross origin requests using JS discourse doesnt allow the Api-Username leading me down the path of the flow described in this thread i.e. using the User-Api-Key and the User-Api-Client-Id

I basically require a description of paramaters PUBLIC_KEY,NONCE,CLIENTID used in the sample request below and where I can get them…

https://forum.domain.com/user-api-key/new?public_key=PUBLIC_KEY&nonce=NONCE&scopes=SCOPES&client_id=CLIENTID&application_name=DEVELOP&auth_redirect=XXX

Finally will this flow allow for seamless api requests from my https://development.domain.com to https://forum.domain.com without the need for authentication.

PS I have SSO set up between the forum and the site from which the requests are being made so the user will be logged in…

Thanks for any guidance

One sec, is this a per user thing? Are you allowing arbitrary users to do this?

Our server API supports header based auth these days so it can work with CORS just like the user api keys do. You would use the user api keys if you want to restrict scopes and allow end users to generate the keys vs admins.

2 „Gefällt mir“

I wouldn’t see each user requiring a separate key no… One admin key should do what I need.

I can consume the api no problem through postman. For example a GET to /notifications.json?username=alanmurphy returns the data no problem using just api-key as a header.

If I trigger that request from the console of a discourse installation I get data back no problem also i.e.

var xhr = new XMLHttpRequest();
xhr.addEventListener(“readystatechange”, function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open(“GET”, “https://**********.com/notifications.json?username=alanmurphy”);
xhr.setRequestHeader(“api-key”, “d06ca53322d1fbaf383a6394d6c229e56871342d2cad953a0fe26c19df7645ba”);
xhr.setRequestHeader(“api-userame”, “system”);
xhr.send();

All Good:+1:

However, if I do this from the sub-domain I am wishing to contact discourse from, it tells me that it has been blocked by CORS policy: Request header field api-key is not allowed by Access-Control-Allow-Headers.

The allowed headers are:

Content-Type, Cache-Control, X-Requested-With, X-CSRF-Token, Discourse-Visible, User-Api-Key, User-Api-Client-Id

If I could just get guidance on what auth params to pass for cross origin requests and where to get them that would be very helpful.

Ps. My discourse is set up to allow Cross Origin requests from the domain so I believe it is purely a headers issue

Thanks

1 „Gefällt mir“