dotnet / aspnetcore

ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.
https://asp.net
MIT License
35.38k stars 10k forks source link

Add logout to Identity API endpoints #52834

Open DaRosenberg opened 10 months ago

DaRosenberg commented 10 months ago

Is there an existing issue for this?

Is your feature request related to a problem? Please describe the problem.

We are building a SPA application using the new Identity API endpoints. As per recommendations for single-origin scenarios, we're using cookies rather than tokens, i.e. calling the /login endpoint with ?useCookies=true. In this scenario, the user logging out is mostly a matter of deleting the authentication cookie.

However, Identity provides no API endpoint to do this, which seems like an omission to us.

So we have to either:

Here's an example workaround we're currently doing for lack of better options:

app.MapIdentityApi<User>();
app.MapPost("/logout", async (SignInManager<User> signInManager) =>
{
    await signInManager.SignOutAsync().ConfigureAwait(false);
});

Describe the solution you'd like

The Identity API endpoints (mapped using MapIdentityApi<User>()) should really include a POST /logout endpoint. This endpoint should invoke all the relevant server-side identity events related to logging out, and should also clear any authentication cookie from the client browser.

Additional context

No response

JosieBigler commented 10 months ago

A default logout would be nice. My solution is very similar.

app.MapPost("/logout", async (SignInManager<IdentityUser> signInManager) =>
{
    await signInManager.SignOutAsync().ConfigureAwait(false);
});
someonestolemyusername commented 9 months ago

I assume the reason there isn't one out of the box is because historically it would lend itself to CSRF denial of service - another website could include your logout URL in an iframe and log your users out. Annoying!

These days, I think most browsers support same site cookies, which stops that kind of CSRF behaviour, so maybe it isn't a huge problem any more for most people?

If you wanted to improve your solution, I would add a .RequireAuthorization() to your endpoint - that way, it won't log your users out unless the auth cookie is sent with the request - meaning, it will only log users out if the request comes from your website with the auth cookie included.

Or, you could add a check in the handler, and if the user is not logged in, simply take no action.

DaRosenberg commented 9 months ago

@someonestolemyusername very insightful, thank you! I have added your improvement to our workaround. 👍🏻

dennisreimann commented 8 months ago

There is a sample logout action in the docs.

This works only for the cookie session. It'd be nice to have a way of invalidating the bearer token too.