Signout using ASP.NET Core Identity

Signout using ASP.NET Core Identity

 Hello Everyone, Welcome to the new blog. In the previous blog we got to know How to authenticate Web API using ASP.NET Core Identity. We also learnt about User confirmation and Password reset. We're able to login to but haven't added any way to SignOut the user after logging in to the application. So, In this blog we'll get to know how we'll implement SignOut functionality in our Web API project using ASP.NET Core Identity.

As we're using ASP.NET Core Identity for Authentication and Authorization in our Web APIs. So, by default ASP.NET Core Identity doesn't provide logout API for implementing logout operation. We've to create the signout endpoint and implement it's functionality to be able to logout from the current logged in session.

For, that we've to create a SignOut controller and add an action mentod named as signout. We can name it as per our requirement. So, let's start adding the controller.

Create a SignOut Controller

    [Authorize]
    [ApiController]
    public class SignOutController : ControllerBase
    {
        private readonly SignInManager<IdentityUser> signInManager;

        public SignOutController(SignInManager<IdentityUser> manager)
        {
            signInManager = manager;
        }

        [HttpPost]
        [Route("signout")]
        public async Task<IActionResult> Signout()
        {
            await signInManager.SignOutAsync();

            return Ok();
        }
    }
The above /signout endpoint will signout the current user form the application. Here we've used SignInManager<TUser> class, which is provided by ASP.NET Core Identity for user SignIn. SignOutAsync() is also implemented in SignInManager<TUser>.

Here IdentityUser contains the user information, by default provided by Identity and also we've configured the same to map our Identity APIs, which you can find in our Autentication using ASP.NET Core Identity blog.

We've also used the [Authorize] attribute, which will ensure that only Authenticated user can access the above endpoint.

Test the /SignOut endpoint

After excecuting the above endpoint as an Authenticated user, it will SignOut the user from the application. If we're using Cookie Based Authentication for login, then it will invalidate/expire the cookie from the user's browser. For, Token Based Authentication, it will invalidate the token on SignOut.

Conclusion

Here we got to know how we'll logout a user from the application using ASP.NET Core Identity. This implementation is only needed to logout a user, rest Identity will handle it behind the scene.

Hope you liked the information. Please share your feedback 

Thank you!


Comments