Example #1
0
        public void SaveTempData(HttpContext context, IDictionary <string, object> values)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var cookieOptions = _options.Cookie.Build(context);

            SetCookiePath(context, cookieOptions);

            var hasValues = (values != null && values.Count > 0);

            if (hasValues)
            {
                var bytes = _tempDataSerializer.Serialize(values);
                bytes = _dataProtector.Protect(bytes);
                var encodedValue = WebEncoders.Base64UrlEncode(bytes);
                _chunkingCookieManager.AppendResponseCookie(context, _options.Cookie.Name, encodedValue, cookieOptions);
            }
            else
            {
                _chunkingCookieManager.DeleteCookie(context, _options.Cookie.Name, cookieOptions);
            }
        }
Example #2
0
        /// <summary>
        /// Creates a session cookie meant to be used to hold the generated JSON Web Token and appends it to the response.
        /// </summary>
        /// <param name="cookieValue">The cookie value.</param>
        private void CreateJwtCookieAndAppendToResponse(string cookieValue)
        {
            CookieBuilder cookieBuilder = new RequestPathBaseCookieBuilder
            {
                Name = _generalSettings.JwtCookieName,
                //// To support OAuth authentication, a lax mode is required, see https://github.com/aspnet/Security/issues/1231.
                SameSite     = SameSiteMode.Lax,
                HttpOnly     = true,
                SecurePolicy = CookieSecurePolicy.SameAsRequest,
                IsEssential  = true,
                Domain       = _generalSettings.HostName
            };

            CookieOptions cookieOptions = cookieBuilder.Build(HttpContext);

            ICookieManager cookieManager = new ChunkingCookieManager();

            cookieManager.AppendResponseCookie(
                HttpContext,
                cookieBuilder.Name,
                cookieValue,
                cookieOptions);

            ApplyHeaders();
        }
        public void AppendResponseCookie(HttpContext context, string key, string value, CookieOptions options)
        {
            var id       = Guid.NewGuid().ToString();
            var cacheKey = GetKey(key, id);

            var expiresUtc   = options.Expires ?? DateTimeOffset.UtcNow.AddMinutes(15);
            var cacheOptions = new DistributedCacheEntryOptions()
                               .SetAbsoluteExpiration(expiresUtc);

            var data = Encoding.UTF8.GetBytes(value);

            var cache = GetCache(context);

            cache.Set(cacheKey, data, cacheOptions);

            // Write the cookie with the identifier as the body
            _cookieManager.AppendResponseCookie(context, key, id, options);
        }
Example #4
0
        // If the javascript issues an OIDC authorize reuest, and it succeeds, the user is already logged
        // into AAD.  Since the AAD session cookie has changed, we need to check if the same use is still
        // logged in.
        public static Task AuthorizationCodeRecieved(AuthorizationCodeReceivedNotification notification)
        {
            // If the successful authorize request was issued by the SingleSignOut javascript
            if (notification.AuthenticationTicket.Properties.RedirectUri.Contains("SessionChanged"))
            {
                // Clear the SingleSignOut Cookie
                ICookieManager       cookieManager = new ChunkingCookieManager();
                string               cookie        = cookieManager.GetRequestCookie(notification.OwinContext, CookieName);
                AuthenticationTicket ticket        = ticketDataFormat.Unprotect(cookie);
                if (ticket.Properties.Dictionary != null)
                {
                    ticket.Properties.Dictionary[OpenIdConnectAuthenticationDefaults.AuthenticationType + "SingleSignOut"] = "";
                }
                cookieManager.AppendResponseCookie(notification.OwinContext, CookieName, ticketDataFormat.Protect(ticket), new CookieOptions());

                Claim existingUserObjectId = notification.OwinContext.Authentication.User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier");
                Claim incomingUserObjectId = notification.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier");

                if (existingUserObjectId.Value != null && incomingUserObjectId != null)
                {
                    // If a different user is logged into AAD
                    if (existingUserObjectId.Value != incomingUserObjectId.Value)
                    {
                        // No need to clear the session state here. It has already been
                        // updated with the new user's session state in SecurityTokenValidated.
                        notification.Response.Redirect("Account/SingleSignOut");
                        notification.HandleResponse();
                    }
                    // If the same user is logged into AAD
                    else if (existingUserObjectId.Value == incomingUserObjectId.Value)
                    {
                        // No need to clear the session state, SecurityTokenValidated will do so.
                        // Simply redirect the iframe to a page other than SingleSignOut to reset
                        // the timer in the javascript.
                        notification.Response.Redirect("/");
                        notification.HandleResponse();
                    }
                }
            }

            return(Task.FromResult <object>(null));
        }
        public void SaveTempData(HttpContext context, IDictionary <string, object> values)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            // Accessing Session property will throw if the session middleware is not enabled.
            var session       = context.Session;
            var cookieOptions = _options.Cookie.Build(context);

            SetCookiePath(context, cookieOptions);

            var hasValues = (values != null && values.Count > 0);

            if (hasValues)
            {
                var bytes = _tempDataSerializer.Serialize(values);
                if (bytes.Length > 4096)
                {
                    session.Set(TempDataSessionStateKey, bytes);
                }
                else
                {
                    bytes = _dataProtector.Protect(bytes);
                    var encodedValue = WebEncoders.Base64UrlEncode(bytes);
                    _chunkingCookieManager.AppendResponseCookie(context, _cookieName, encodedValue, cookieOptions);
                }
            }
            else
            {
                session.Remove(TempDataSessionStateKey);

                if (context.Request.Cookies.ContainsKey(_cookieName))
                {
                    _chunkingCookieManager.DeleteCookie(context, _cookieName, cookieOptions);
                }
            }
        }
Example #6
0
        /// <summary>
        /// Creates a session cookie meant to be used to hold the generated JSON Web Token and appends it to the response.
        /// </summary>
        /// <param name="cookieValue">The cookie value.</param>
        private void CreateJwtCookieAndAppendToResponse(string cookieValue)
        {
            CookieBuilder cookieBuilder = new RequestPathBaseCookieBuilder
            {
                Name         = "AltinnStudioRuntime",
                SameSite     = SameSiteMode.Lax,
                HttpOnly     = true,
                SecurePolicy = CookieSecurePolicy.None,
                IsEssential  = true,
                Domain       = _generalSettings.HostName,
                Expiration   = new TimeSpan(0, 1337, 0)
            };

            CookieOptions cookieOptions = cookieBuilder.Build(HttpContext);

            ICookieManager cookieManager = new ChunkingCookieManager();

            cookieManager.AppendResponseCookie(
                HttpContext,
                cookieBuilder.Name,
                cookieValue,
                cookieOptions);
        }
Example #7
0
        private byte[] GetOrCreateSessionId(IDotvvmRequestContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            var sessionIdCookieName = GetSessionIdCookieName(context);

            if (string.IsNullOrWhiteSpace(sessionIdCookieName))
            {
                throw new FormatException("Configured SessionIdCookieName is missing or empty.");
            }

            // Get cookie manager
            var mgr = new ChunkingCookieManager(); // TODO: Make this configurable

            // Get application key helper
            var keyHelper = new ApplicationKeyHelper(context.Configuration.Security);

            // Get cookie value
            var sidCookieValue = mgr.GetRequestCookie(context.OwinContext, sessionIdCookieName);

            if (string.IsNullOrWhiteSpace(sidCookieValue))
            {
                // No SID - generate and protect new one
                var rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
                var sid = new byte[SID_LENGTH];
                rng.GetBytes(sid);
                var protectedSid = keyHelper.ProtectData(sid, KDF_LABEL_SID);

                // Save to cookie
                sidCookieValue = Convert.ToBase64String(protectedSid);
                mgr.AppendResponseCookie(
                    context.OwinContext,
                    sessionIdCookieName, // Configured cookie name
                    sidCookieValue,      // Base64-encoded SID value
                    new Microsoft.Owin.CookieOptions
                {
                    HttpOnly = true,                                    // Don't allow client script access
                    Secure   = context.OwinContext.Request.IsSecure     // If request goes trough HTTPS, mark as secure only
                });

                // Return newly generated SID
                return(sid);
            }
            else
            {
                // Try to read from cookie
                try
                {
                    var protectedSid = Convert.FromBase64String(sidCookieValue);
                    var sid          = keyHelper.UnprotectData(protectedSid, KDF_LABEL_SID);
                    return(sid);
                }
                catch (Exception ex)
                {
                    // Incorrect Base64 formatting of crypto protection error
                    throw new SecurityException("Value of the SessionID cookie is corrupted or has been tampered with.", ex);
                }
            }
        }
Example #8
0
        private byte[] GetOrCreateSessionId(IDotvvmRequestContext context, bool canGenerate = true)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            var sessionIdCookieName = GetSessionIdCookieName(context);

            if (string.IsNullOrWhiteSpace(sessionIdCookieName))
            {
                throw new FormatException("Configured SessionIdCookieName is missing or empty.");
            }

            // Get cookie manager
            var mgr = new ChunkingCookieManager(); // TODO: Make this configurable

            // Construct protector with purposes
            var userIdentity    = ProtectionHelpers.GetUserIdentity(context);
            var requestIdentity = ProtectionHelpers.GetRequestIdentity(context);
            var protector       = this.protectionProvider.Create(PURPOSE_SID);

            // Get cookie value
            var sidCookieValue = mgr.GetRequestCookie(context.GetOwinContext(), sessionIdCookieName);

            if (!string.IsNullOrWhiteSpace(sidCookieValue))
            {
                // Try to read from cookie
                try
                {
                    var protectedSid = Convert.FromBase64String(sidCookieValue);
                    var sid          = protector.Unprotect(protectedSid);
                    return(sid);
                }
                catch (Exception ex)
                {
                    // Incorrect Base64 formatting of crypto protection error
                    // Generate new one or thow error if can't
                    if (!canGenerate)
                    {
                        throw new SecurityException("Value of the SessionID cookie is corrupted or has been tampered with.", ex);
                    }
                    // else suppress error and generate new SID
                }
            }

            // No SID - generate and protect new one

            if (canGenerate)
            {
                var rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
                var sid = new byte[SID_LENGTH];
                rng.GetBytes(sid);
                var protectedSid = protector.Protect(sid);

                // Save to cookie
                sidCookieValue = Convert.ToBase64String(protectedSid);
                mgr.AppendResponseCookie(
                    context.GetOwinContext(),
                    sessionIdCookieName,                                // Configured cookie name
                    sidCookieValue,                                     // Base64-encoded SID value
                    new Microsoft.Owin.CookieOptions
                {
                    HttpOnly = true,                                   // Don't allow client script access
                    Secure   = context.HttpContext.Request.IsHttps     // If request goes trough HTTPS, mark as secure only
                });

                // Return newly generated SID
                return(sid);
            }
            else
            {
                throw new SecurityException("SessionID cookie is missing, so can't verify CSRF token.");
            }
        }
Example #9
0
 public void AppendResponseCookie(IOwinContext context, string key, string value, CookieOptions options)
 {
     options.Domain = context.Request.Uri.GetHostWithoutSubDomain();
     _chunkingCookieManager.AppendResponseCookie(context, key, value, options);
 }
 public void AppendResponseCookie(HttpContext context, string key, string value, CookieOptions options)
 {
     _cookieManager.AppendResponseCookie(context, key, value, options);
 }
 public void AppendCookies()
 {
     _chunkingCookieManager.AppendResponseCookie(_httpContext, "TestCookie1", _stringToAdd, _cookieOptions);
     _httpContext.Response.Headers[HeaderNames.SetCookie] = StringValues.Empty;
 }
Example #12
0
        public void AppendResponseCookie(HttpContext context, string key, string value, CookieOptions options)
        {
            GenericizeDomain(context, options);

            manager.AppendResponseCookie(context, key, value, options);
        }