I need a URL that will return 200 for a logged in user and 401 or 403 if the user is not logged in.
If require_login is checked, every page does a 301 to the login page.
I need a URL that will return 200 for a logged in user and 401 or 403 if the user is not logged in.
If require_login is checked, every page does a 301 to the login page.
Is this a user request, i.e. using the current users session?
Or…
Is this an admin API request using an admin API key?
Yeah. It’s me not understanding the question I’m asking.
I’m trying to do an auth_request in NGINX to tell whether the request is coming from a user that’s logged in by querying an URL to see whether it gets a 200 response or not.
It’s occurring to me that doing that is not quite as simple as I’d hoped.
You could try /session/current.json
It will return 200 if authenticated and 404 if not.
Generally .json / API requests don’t redirect.
That seems promising. I’ll keep poking at it.
Many thanks!
Is there an easy way to do this from a different subdomain?
Example, the forum is at forum.example.com and the request is coming from example.com (either from the frontend or backend code).
Sure. You can make an API call from anywhere.
But this specific call needs to be done from the frontend, since it will use the session cookies sent by the browser to the forum.
The Discourse session cookie appears to be just for the subdomain, so would the cookie be accessible from the top-level domain? I see _forum_session on the Discourse subdomain but it doesn’t appear when visiting the TLD.
If the cookie were available on the top-level domain, I was thinking that it would also be passed to the backend, so the backend could forward it to Discourse, but I’m not sure.
Maybe it requires using Discourse as an SSO provider? If it isn’t known whether the user is logged in, then we could redirect through the SSO process to check. I’m currently setting it up on a test server to see if it would work.
Edit: my end goal is to generate a JWT with the user data from Discourse (only if logged in to Discourse) and pass it to Firebase. There is a Discourse server on the subdomain, an extra backend server that can perform additional logic, and an SPA that connects to Firebase if given a JWT.
If you want anything fancy like this you would need to implement your own CurrentUserProvider
Thanks, I just looked it up and found this other thread, so I’ll ask some more questions about it over there.
Edit: it looks like we can do what we need with Discourse as an SSO provider.
If you can do it with SSO I highly recommend you go that path vs a provider
Thanks, it looks like we can check if a user is logged in and then redirect through Discourse’s SSO route if not logged in. It seems to work well on my laptop. The user logout webhook from Discourse can then log them out of the other app.
Не могли бы вы немного пояснить, как можно проверить, что пользователь вошёл в систему на Discourse с другого поддомена? Я пытаюсь реализовать middleware аутентификации в моих обработчиках маршрутов (на стороне сервера), чтобы проверить, действителен ли ещё вход пользователя в Discourse через SSO.
Я пытаюсь реализовать практически то же самое для веб-приложения, но не могу понять, как проверить, что пользователь всё ещё вошёл в систему. (Желательно, чтобы вход был выполнен из того же браузера, который в данный момент используется для отправки запроса на сервер.)
Спасибо!
Мой код для этого ещё не запущен, но если пользователь перенаправляется через другой сервер (где Discourse выступает провайдером единого входа), то на этом внешнем сервере будет создана сессия. Я создал там маршрут, например /auth/is-authenticated, который возвращает статус пользователя. Он в основном нужен для того, чтобы скрывать кнопки «Войти», когда пользователь уже авторизован. Когда пользователь выходит из Discourse, я думаю, что вебхук также выводит его из системы на другом сервере. Я давно не проверял код, но, насколько я помню, именно так я всё настроил.
Как внешний сервер может проверить, что браузер пользователя всё ещё вошёл в систему в Discourse? Мне кажется, что другой домен даже не может получить доступ к кукам Discourse, установленным после входа.
Моя цель — разлогинить пользователя с внешнего (не Discourse) сервера, если пользователь вышел из системы в Discourse, используя только текущий активный браузер. (Возможно ли это вообще?)
Спасибо за ответ.
Когда пользователь находится во внешнем приложении, он нажимает кнопку входа и перенаправляется через поток SSO-провайдера Discourse, после чего возвращается во внешнее приложение. Это внешнее приложение может хранить сессию с данными пользователя. Когда пользователь выходит из Discourse, вебхук может удалить сессию внешнего приложения. Я не уверен, но, кажется, заголовок вебхука — X-Discourse-Event: user_logged_out.
Редактирование: выход из внешнего сайта осуществляется с помощью API Discourse.
Вместо того чтобы спрашивать у Discourse, вошёл ли пользователь в систему, можно запросить эту информацию у внешнего приложения. В моём случае это нужно, например, для скрытия кнопки входа на внешнем сайте.
Я смогу позже перепроверить свой код. Я давно не смотрел его, но, кажется, он делал что-то подобное.
Спасибо за ответ! Очень признателен.
Да, теперь мне всё понятно. Единственный нюанс при выходе через API заключается в том, что пользователь будет разлогинен из всех сессий (на всех устройствах, поскольку API не может различить сессию текущего браузера и сессии других открытых браузеров).