Sunday, December 3, 2017

AspNet Identity MVC - How to catch Signed In Event

Leave a Comment

I am using ASPNet Identity 2.0 (Full framework, not the core framework) and MVC. I would like to execute C# code once the user successfully login to the site.

i know that i can write some code right after the SignInManager.PasswordSignInAsync command and it will work for new login but not will not work for users who used "remember me" feature and returned to the site later (Cookie authentication).

I am looking for an option to catch the event of all the users who signed in to the site either by entering the password and by using the "remember me" cookie.

2 Answers

Answers 1

There are many ways to do it. You can create and use custom attribute.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]     public class CustomAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter     {         readonly IAuthentication _authentication;          public CustomAuthorizeAttribute(IAuthentication authentication)         {             _authentication = authentication;         }          public override void OnAuthorization(AuthorizationContext filterContext)         {             if (!_authentication.Authorize(filterContext.HttpContext))                 filterContext.Result = new HttpUnauthorizedResult();           //your code .....         }     } 

And now rather than using [Authorize] use your new [CustomAuthorizeAttribute] attribute

[CustomAuthorizeAttribute] public ActionResult Index() {     ViewBag.Title = "Welcome";     ViewBag.Message = "Welcome to ASP.NET MVC!";         return View(); } 

Answers 2

One way you can do it is by handling the application event in your global.asax file.

protected void Application_AuthenticateRequest(object sender, EventArgs e)         {             if (Request.IsAuthenticated)             {                 Response.Write("HELLO");             }         } 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment