python-social-auth / social-core

Python Social Auth - Core
BSD 3-Clause "New" or "Revised" License
851 stars 546 forks source link

How to catch `AuthStateForbidden` exception during authentication process #825

Closed joachimBurket closed 1 year ago

joachimBurket commented 1 year ago

Expected behaviour

Being able to catch AuthStateForbidden exception during authentication, and redirect user to another URL.

Actual behaviour

My Django server sometimes reports 500 internal errors during the authentication process:

Internal Server Error: /oauth/complete/azuread-v2-tenant-oauth2/

AuthStateForbidden at /oauth/complete/azuread-v2-tenant-oauth2/
Wrong state parameter given.

I'm not sure, but I think it may be that some users have the "auth complete URL" saved in their browser history, and try to access the site with this URL instead of the "Home URL". Therefore, the state in the "auth complete URL" is no longer valid and the server returns a 500 error.

I would like to redirect the user to the "Home URL" instead of returning a 500 error (or maybe displaying a page saying that the authentication state is no longer valid, and a link redirecting to the home).

What are the steps to reproduce this issue?

Try to access directly the "auth complete URL" with an invalid state, for instance:

https://site.example.org/oauth/complete/<backend>/?code=1234&state=1234&session_state=1234

Any other comments?

Here are the versions used:

And the SOCIAL_AUTH_PIPELINE:

SOCIAL_AUTH_PIPELINE = (
    "agrume.social_auth_pipelines.social_details",
    "agrume.social_auth_pipelines.social_uid",
    "social_core.pipeline.social_auth.social_user",
    "social_core.pipeline.user.get_username",
    "social_core.pipeline.social_auth.associate_by_email",
    "social_core.pipeline.user.create_user",
    "social_core.pipeline.social_auth.associate_user",
    "social_core.pipeline.social_auth.load_extra_data",
    "social_core.pipeline.user.user_details",
)
nijel commented 1 year ago

At Weblate we ended up with wrapping up the whole authentication view: https://github.com/WeblateOrg/weblate/blob/d23693c5fe27dbab0957a9c274af94aba84169b2/weblate/accounts/views.py#L1244-L1331

joachimBurket commented 1 year ago

Hi @nijel, thanks for your example! I was able to reproduce the wrapper of the complete view in my code and catch the AuthStateForbidden exception.