How can an API user create posts as another user?

I’m using the API of Discourse with a custom UI. I’m attempting to integrate this behind an orchestration layer that already authenticates users. I’d like to be able to more or less bypass authentication on the Discourse side of things.

We use JWT tokens, and it seems that ideally I could just pass these along to Discourse and tell it to trust them. I see that there’s some JWT related projects in the discourse GitHub organization, but there’s no documentation or usage examples, Google hasn’t been helpful, I haven’t found any relevant threads in meta, and I don’t really speak Ruby :frowning:

Is there a way I could leverage our existing authentication by just passing these tokens through to Discourse?

Failing that, as an API user, how can I create topics and posts on behalf of other, authenticated users?

1 Like

One strategy I’m exploring is creating an API user for every user in my system. Any obvious downsides to this?

You could use a master API key, and specify the username of the user you are impersonating – the master API key should always work.

7 Likes

Okay, that’s interesting. How would you specify the user name? As the api_username parameter on the query string?

Yes, exactly. This is the name of the user performing the action, while the API key just proves you’re allowed to speak for that user.

6 Likes

Excellent, that sounds perfect. I’ll try it out.

I’m trying to do this, but I cannot specify an arbitrary username as api_username - if I specify any username other than my (admin) account, I get a 404 from the API.

Is this post out of date, or is there some other way to achieve creating topics as another user (other than creating an API key for every user)?

I think the API has changed since the post was originally created. Nowadays you have to specify the username via the HTTP header Api-Username:…

3 Likes

Hi everyone,

I am writing because I am trying to populate my forum with posts made by a set of users from another old forum.

On the docs it is explained how to create a post via the API, but I am unsure on how to do it make these posts appear as being from a specific user. The solution proposed above seems to no longer work.

Is there a field where I could enter the user name? I can’t find it in the docs.

Thank you for your help!

Have you considered trying a migration script?

https://github.com/discourse/discourse/tree/master/script/import_scripts

This might be a lot simpler. And there are many step by step tutorials here on Meta depending on what platform the old forum runs on.

3 Likes

If you create an API key for “All Users”:

You can then specify the username you want to create posts for via the Api-Username header when making the api request.

1 Like

Thank you @blake, I think that’s the road I’ll take
@justin thank you, I’d rather stick to the APIs, for the moment, but will keep the importer in mind for the future!

3 Likes