ASP.NET authentication How do I get around a custom cookie claim without adding it to the data warehouse?

Using ASP.NET Identity 2.1.0,

I am trying to add a custom claim so that it is added to the rounding cookie and not added to the data store.

The claim is intended for a unique session identifier, a unique login, even if for the same UserId (for a better audit of operations performed on each Session / Client IP address).

Trying so far:

            Provider = new CookieAuthenticationProvider
            {
                OnResponseSignIn = (x) =>
                {

                    //Let pretend this is a Session table Id:
                    var st = x.Identity.FindFirstValue("ST");
                    if (string.IsNullOrEmpty(st))
                    {
                        //Damn! always needs regeneration because not round-tripping coming back :-(
                        //Could use Session, but that defeats the purpose of using a cookie...
                        st = Guid.NewGuid().ToString();
                    }
                    x.Identity.AddClaim(new Claim("ST", st));
                    x.OwinContext.Authentication.SignIn(x.Identity);
                },
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.  
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromSeconds(6),
                    regenerateIdentity: async (manager, user) =>
                    {

                        var x = await user.GenerateUserIdentityAsync(manager);
                        return x;
                    }
                    )
            }
        });   

using the cache (Session / load balanced Shared / etc.) for SessionId, using UserId, since the key will obviously not work (it will return the same SessionId, regardless of ClientIP)

using UserId + ClientIP, because the key will return SessionId ... But ClientIP is noticeably error prone, so it will fail.

cookie, , , cookie - , , , ....

- (, ) ?

, Cookie Identity, , , ? ?

!

+4
2

user.GenerateUserIdentityAsync(manager); . , .

IClaimsIdentityFactory UserManager.ClaimsIdentityFactory. ClaimsIdentityFactory

, " ".

0

, cookie Identity ASP.NET , ( Identity + Claims, ), , , , :

OnResponseSignIn = (x) =>
{
    string key = "SessionId";
    string serializedSessionId;
    var cookie = x.OwinContext.Request.Cookies.SingleOrDefault(y => y.Key == key);
    if (!string.IsNullOrEmpty(cookie.Value))
    {
        var serializedAndEncryptedText = cookie.Value;
        serializedSessionId = /*decode*/ serializedAndEncryptedText;
        //...maybe update the Session record last known Activity date?
        //and or check that the value contains the SessionId:UserId, and if UserId has changed,
        //rebuild a new Session (that in case Sign out fails to destroy all occurances of it)...
    }
    else
    {
        var check = x.OwinContext.Request.Environment;
        serializedSessionId = new SessionService().CreateSession(HttpContext.Current.Request.UserHostAddress).ToString(); //pretend that we hit the db...
        //TODO: how can we encrypt this value so that it safer than just ClearText?
        string serializedAndEncryptedText = serializedSessionId; 
        cookie = new KeyValuePair<string, string>(key,serializedAndEncryptedText);
        x.Response.Cookies.Append(cookie.Key, cookie.Value);  
    }
    //TODO: what not good is that we have to remember to destroy the cookie
    //every time we sign out...there risk we don't catch every single occurance of it
    //(eg: if the underlying Manager is invoked, rather than the ApplicationManager)

    serializedSessionId = cookie.Value;
    x.Identity.AddClaim(new Claim(key, serializedSessionId));
    x.OwinContext.Authentication.SignIn(x.Identity);
},

cookie, Login, ExternalLogin Logout - :

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult LogOff()
    {

        var sessionIdCookie = this.HttpContext.Request.Cookies["SessionId"];
        if (sessionIdCookie != null)
        {
            sessionIdCookie.Value = string.Empty;
            sessionIdCookie.Expires = DateTime.Now.AddYears(-1);
            this.HttpContext.Response.Cookies.Add(sessionIdCookie);
        }
        AuthenticationManager.SignOut();

        return RedirectToAction("Index", "Home");
    }

Sesionservice , , DI :

public class SessionService
{
    public Guid CreateSession(string clientIP)
    {
        Session session =new Session();
        session.DateTimeStartedUtc = DateTime.UtcNow;
        session.ClientIP = clientIP;
        ApplicationDbContext applicationDbContext = new ApplicationDbContext();
        applicationDbContext.Set<Session>().Add(session);
        applicationDbContext.SaveChanges();
        return session.Id;
    }   
}

POC-, , MVC-, Cookies . , SPA ( , / -, ).

- - - , , ... (, ...:-))

.

0

All Articles