-->

MVC5 Identity/OWIN - Signout events

2020-07-31 06:09发布

问题:

How to detect all possible SignOuts? Is there a way to get some event when SignOut is made manually, by timeout and any other possible ways?

I need to know when user authentication ends like i know that it starts when SingIn is called.

I'm using both internal accounts and external (like Facebook).

回答1:

I need a spot that i can initialize user session when user is already authenticated. Below is code that should do the job, i don't like it at all. I need to check session at each request to be sure that flag in session is already loaded and was loaded for current user.

In future that flag will be probably a whole class of properties from DB.

Can't believe that there is no better way of detecting when user is SignedIn/Out.

What i've done is:

void Session_Start(object sender, EventArgs e)
{
    InitializeSession_Authenticated();
}

protected void Application_AcquireRequestState(Object sender, EventArgs e)
{
    InitializeSession_Authenticated();
}

private void InitializeSession_Authenticated()
{
    if (HttpContext.Current.Session == null)
        return;
    if (!System.Threading.Thread.CurrentPrincipal.Identity.IsAuthenticated)
        return;

    string userName = System.Threading.Thread.CurrentPrincipal.Identity.Name;
    if (HttpContext.Current.Session[SESSION_VAR.USER_ISINITIALIZED] == null || 
        HttpContext.Current.Session[SESSION_VAR.USER_NAMEFORSESSION] != userName)
    {
        HttpContext.Current.Session[SESSION_VAR.USER_NAMEFORSESSION] = userName;
        HttpContext.Current.Session[SESSION_VAR.USER_ISINITIALIZED] = GetFlagFromDB(userName);
    }
}

EDIT: @Shoe thanks :P...