# Can I use the Discourse API to authenticate users in another app?

**URL:** <https://meta.discourse.org/t/can-i-use-the-discourse-api-to-authenticate-users-in-another-app/266322>\
**Category:** SSO\
**Created:** [May 26, 2023, 2:29pm UTC](https://meta.discourse.org/t/can-i-use-the-discourse-api-to-authenticate-users-in-another-app/266322 "2023-05-26T14:29:17Z")\
**Posts on this page:** 1\
**Showing post:** 12

<div class="post-metadata">

**Author:** ![ygramoel](https://avatars.discourse-cdn.com/v4/letter/y/74df32/32.png) [@ygramoel](https://meta.discourse.org/u/ygramoel)\
**Post date:** [May 30, 2023, 10:27am UTC](https://meta.discourse.org/t/can-i-use-the-discourse-api-to-authenticate-users-in-another-app/266322/12 "2023-05-30T10:27:34Z")

</div>

Here are 20 lines of Python code that do approximately the same as the React Native code referred to by @renato (except no compatibiliy with Discourse 2.5 - I don’t need that)

It works well, assuming that you are using basic username-password based login. I will still look into the alternative methods, using the [Discourse SSO](https://meta.discourse.org/t/13045?silent=true) login as configured in the Discourse instance.

```plaintext
import requests
import json

def discourse_authenticate(url, name, password):
    session = requests.Session()
    session.headers.update({'X-Requested-With': 'XMLHttpRequest'})
    r1 = session.get(url + '/session/csrf')
    csrf_token = json.loads(r1.text).get('csrf')
    r2 = session.post(url + '/session',
        data={
            'login': name,
            'password': password,
            'authenticity_token': csrf_token,
        },
    )
    if r2.status_code != 200:
        return None
    return json.loads(r2.text)

```

---

_[View the full topic](https://meta.discourse.org/t/can-i-use-the-discourse-api-to-authenticate-users-in-another-app/266322)._
