Question

In an MVC app UserId of current user can be obtained using WebSecurity.UserId, but if I do that during the login action it will return -1. The reason for that is explained here and here. Basically the authorization cookie is set during login, but the framework will have access to it no sooner than during the next request. I can somewhat get around not having UserId in login action by pulling the user from database based on his\hers name.

However I can't do the same when it comes to external login as I don't have easy access to user's name. For various reasons I need to run two functions that take UserId as input and I need to do so right after login using external account. I'd prefer if I could somehow do so within the external login action. So, is there any way to get UserId of the user who just logged in without reloading page (redirecting somewhere else)?

I have also this problem which I could probably solve if I could get my hands on UserId of the currently logged user (even if his authorization cookie was just set during current request). Because of this, I was looking for some more general solution rather than just finding ways to extract user's email from google and facebook callback data during the external login.

Was it helpful?

Solution

Semi-solution to my problem, getting user profile after login using external account:

public ActionResult ExternalLoginCallback()
{
    AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback"));
    if (!result.IsSuccessful)
    {
        return RedirectToAction("ExternalLoginFailure");
    }
    if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
    {
        var db = new MyDataClassesDataContext();
        var user = db.ExecuteQuery<UserProfile>("SELECT TOP 1 up.* FROM [dbo].webpages_OAuthMembership oam JOIN [dbo].UserProfile up ON (up.UserId = oam.UserId) WHERE oam.ProviderUserId = '" + result.ProviderUserId + "'").FirstOrDefault();
        // Do your post login stuff here
        return RedirectToAction("SomewhereAfterLogin");
    }
    // Here goes creating a new account in case external wasn't in the system before
}

This however doesn't solve the problem of server having rare random restarts that cause authorization cookie to disappear where I don't know user's id without making a redirect (which causes problems in my app as explained here).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top