Especificação das chaves de API de usuário

O Discourse contém um sistema para gerar chaves de API por usuário se um protocolo muito específico for seguido. Este recurso facilita o acesso de “aplicativos” às instâncias do Discourse sem a necessidade de envolver moderadores.

Descrição de alto nível

Em alto nível:

  1. O cliente (aplicativo de desktop, plugin de navegador, aplicativo móvel) gera um par de chaves privada/pública e uma URL de retorno
  2. O cliente redireciona para uma rota no Discourse fornecendo ao Discourse sua chave pública
  3. O Discourse obtém a aprovação do usuário para usar o aplicativo
  4. O Discourse gera uma chave de API de usuário
  5. O Discourse redireciona de volta para a URL de retorno com um payload criptografado usando a chave pública contendo a chave de API do usuário

Detalhes

Casos de uso:

  1. Aplicativos de desktop que consultam sites do Discourse em nome de usuários finais para obter contagens de notificações em vários sites.
  2. Aplicativos móveis que consultam sites do Discourse em nome de usuários finais e gerenciam notificações push.
  3. Aplicativos da web que fornecem um painel para usuários finais sobre vários sites do Discourse.
  4. Integrações personalizadas com aplicativos de terceiros que consomem o Discourse como parte de um aplicativo corporativo geral. Ex: integrar notificações da comunidade do Discourse ao aplicativo hopscotch.

O design:

Configurações do Site

  • allow_user_api_key_scopes: escopos de acesso permitidos para chaves de API de usuário. Os escopos são definidos aqui. Os escopos integrados disponíveis são: read, write, message_bus, push, one_time_password, notifications, session_info, bookmarks_calendar, user_status (plugins podem registrar escopos adicionais).

  • user_api_key_allowed_groups: controla quais grupos estão autorizados a gerar chaves de API de usuário (o padrão é administradores, moderadores e nível_de_confiança_0)

  • allowed_user_api_push_urls: lista de sites que podem ser destinos para notificações push

  • allowed_user_api_auth_redirects: destinos de redirecionamento permitidos após a geração da chave de API do usuário

Configurações Globais

  • max_user_api_reqs_per_minute: 20
  • max_user_api_reqs_per_day: 2880

Elementos de UX

Se alguma chave de API de usuário tiver sido concedida, o Discourse exibe uma aba apps (aplicativos) na página do usuário.
A aba apps (aplicativos) listará:

  • O nome do aplicativo, por exemplo: (“Discourse Notifier”)
  • Data do último uso
  • Data de aprovação
  • Lista de escopos de acesso concedidos
  • Um botão revoke access (revogar acesso) para que você possa revogar facilmente quaisquer chaves

UI de autorização da chave de API

Cada chave terá que ser explicitamente autorizada pelos usuários finais em uma página que explica claramente o que está acontecendo, por exemplo:

“Discourse Notifier” está solicitando o seguinte acesso à sua conta:

  • Ler e limpar notificações
  • Ler informações de sessão do usuário
  • Criar um token de login único

[Autorizar]

Fluxo de geração de chave de API

A API requer apenas uma única solicitação GET do lado do usuário.

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

:exclamation: A partir do Discourse 2.1, essas chaves de API de usuário agora expiram automaticamente se ficarem sem uso por longos períodos. A configuração do site: revoke user api keys unused days é definida como 180 por padrão.

Parâmetros:

  • auth_redirect: URL para redirecionar de volta com o token gerado
  • application_name: o nome do aplicativo que está fazendo a solicitação (será exibido na aba Aplicativos da conta do usuário)
  • client_id: um identificador exclusivo para o cliente
  • nonce: um nonce exclusivo gerado pelo cliente. Ele será repetido no payload criptografado para que o cliente possa verificar a autenticidade da resposta
  • scopes: lista separada por vírgulas de escopos de acesso permitidos para a chave, consulte allow user api key scopes para a lista completa de escopos disponíveis
  • push_url: URL para enviar notificações push (obrigatório e válido somente se push ou notifications estiverem incluídos nos escopos)
  • public_key: a parte pública do par de chaves gerado pelo cliente
  • padding (opcional): o modo de preenchimento RSA a ser usado para criptografar o payload. Valores aceitos são pkcs1 (padrão) ou oaep. OAEP é recomendado para novos aplicativos.

Após /user-api-key/new ser chamado com os parâmetros corretos, 2 coisas podem acontecer

  1. Se o usuário não estiver logado, seremos redirecionados para o login (após o login, retomaremos a autorização)
  2. Assim que um usuário estiver logado, ele verá a UI de autorização

Após a autorização ser permitida, o sistema redirecionará de volta para a URL definida em auth_redirect e incluirá um parâmetro payload criptografado contendo um objeto JSON com a chave de API do usuário gerada (key), o nonce, o status push (push) e a versão da API (api). Se o escopo one_time_password foi solicitado, um parâmetro de consulta oneTimePassword criptografado separado também será incluído. client_id não é repetido para segurança extra.

Verificando a versão da API

A API de chave de uso no Discourse é versionada. Os clientes podem verificar a versão da API de um site do Discourse fazendo uma solicitação HEAD para https://sitename.com/user-api-key/new. A resposta conterá um cabeçalho chamado Auth-Api-Version contendo o número da versão da API do site.

Consumindo a API

O consumo da API do cliente será um pouco diferente da API de administrador atual.
O cliente pode especificar 2 cabeçalhos:

User-Api-Key (obrigatório): a chave que foi gerada

e

User-Api-Client-Id (opcional): forneça isso para atualizar o ‘client id’ armazenado para esta api_key no banco de dados.

Assim que esses cabeçalhos forem especificados, o cliente poderá realizar solicitações contra a API normalmente.

Gerando uma senha de login única

A partir da versão 4, a API inclui um escopo especial: o escopo one_time_password, que permite aos clientes usar a chave de API do usuário para gerar uma senha de uso único (one-time-password). Se o cliente incluir este escopo ao gerar a chave de API seguindo as etapas acima, uma oneTimePassword criptografada será incluída como um parâmetro de consulta separado no redirecionamento de volta para o cliente.

Alternativamente, o cliente pode fazer uma solicitação GET para /user-api-key/otp com os seguintes parâmetros:

  • auth_redirect
  • application_name
  • public_key
  • padding (opcional)

e com o cabeçalho User-Api-Key.

Esta solicitação redirecionará para uma tela no Discourse que pedirá ao usuário para permitir que o aplicativo acesse o site. Se o usuário aprovar, o site redirecionará de volta para a URL definida em auth_redirect e incluirá um parâmetro oneTimePassword criptografado com uma senha de uso único que o cliente pode usar para fazer login no site solicitando https://sitename.com/session/otp/ONE-TIME-PASSWORD. (A senha de uso único é válida apenas por 10 minutos.)

Revogando chaves de API

Para revogar uma chave de API, faça uma solicitação POST com o cabeçalho User-Api-Key e nenhum parâmetro para /user-api-key/revoke.


Última Revisão por @SaraDev em 2022-07-13T00:00:00Z

30 curtidas
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 curtidas

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

1 curtida

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

1 curtida

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

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

4 curtidas

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

2 curtidas

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

2 curtidas

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 curtida

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 curtidas

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 curtidas

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 curtidas

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 curtida

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 curtidas

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 curtidas

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 curtida