How to track expired WIF fedauth cookies?

被刻印的时光 ゝ 提交于 2019-12-03 08:18:33

You don't without keeping a server-side list of the tokens recently revoked. This is why normally we rely upon an inherent expiration as well as HTTPS to prevent the token from being leaked/stolen.

I was tasked with a similar request by our security team. I opted to store the asp.net session id in the OWIN cookie and on each request that contained a session id in the cookie I verify it matches the active session's Id.

Store session id in the cookie (adapted from this answer) at the end of the first request that is authenticated and doesn't already have the session id in the cookie:

protected override void OnActionExecuted(ActionExecutedContext filterContext)
    { 
        base.OnActionExecuted(filterContext);

        bool authenticated = User.Identity.IsAuthenticated;

        var sessionGuid = (User as ClaimsPrincipal).FindFirst("sessionID")?.Value;

        //put the SessionID into the cookie.
        if (authenticated && string.IsNullOrEmpty(sessionGuid))
        {
            var id= Session.SessionID;

            //update the guid claim to track with the session
            var authenticationManager = HttpContext.GetOwinContext().Authentication;

            // create a new identity from the old one
            var identity = new ClaimsIdentity(User.Identity);

            // update claim value
            identity.RemoveClaim(identity.FindFirst("sessionID"));
            identity.AddClaim(new Claim("sessionID", id));

            // tell the authentication manager to use this new identity
            authenticationManager.AuthenticationResponseGrant =
                new AuthenticationResponseGrant(
                    new ClaimsPrincipal(identity),
                    new AuthenticationProperties { IsPersistent = true }
                );
        }
    } 

Then on each future request if I find a session in the cookie compare it to active session. If they don't match then logout:

protected override void OnActionExecuting( ActionExecutingContext filterContext)
    {
        var claim = (User as ClaimsPrincipal).FindFirst("sessionID")?.Value;

        //does the owin cookie have a sessionID?
        if (!string.IsNullOrEmpty(claim))
        {
            string session = Session.SessionID;

            //does it match the one stored in the session?
            if(session != claim)
            {
                //no? log the user out again..
                Session.Abandon();

                //redirect to logged out page
                this.Request.GetOwinContext().Authentication.SignOut();

                //tell them its over..
                Response.Write("Expired Session");

                Response.End();
            }
        }

        base.OnActionExecuting(filterContext);
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!