In December 2020, I moved into an apartment with an amazing view. I could see Birmingham's famous Vulcan statue from my balcony! When summer came, I decided to create a balcony garden to make my outdoor space more enjoyable.
Time seems to be passing ever more quickly.
I know I'm not the only one who feels this way. But what is the explanation for this seemingly universal aspect of human experience?
In my quest for the answer I did a little googling and found this nifty article on Lifehacker. According to psychologists who study time perception, the reason time passes more quickly as we age is that adult life is more routinized.
Fortunately, there are things we can do to slow down the passage of time. We can mix up our routines, seek out novel experiences, take plenty of photos, keep a journal, and, of course, meditate.
If you want to develop a secure web application, you need to make sure your cookies are locked down tight.
Because web applications use the client-server model, they are stateless. So we use sessions to persist data from one request to the next. The most common method for identifying a session is to create a unique session ID. Obviously this ID is stored on the server, either directly on the filesystem or in a database. But how will it be stored on the client side? That's where cookies come in.
Clearly, it is of supreme importance that we make our cookies secure. So what defines a "secure" cookie? Like everything else in the world of security, this depends on context. There are no quick fixes or easy answers. To really be confident that your cookies are secure, you need to do your own research and base your approach on the specifics of your situation. That being said, the purpose of this post is to provide a decent starting point. I will focus on the following and describe how each can be implemented in Laravel:
Why should we use prefixes?
Every cookie has a name. We can add prefixes to the names of our cookies to make them more secure. These prefixes tell the browser to reject the cookies if they do not meet certain requirements. The obvious limitation here is that this assumes that the user is using a browser that supports these prefixes.
There are two supported prefixes. Each begins with two underscores and ends with a hyphen:
__Secure- prefix, perhaps counterintuitively, is the less restrictive of the two.
Compliant browsers will reject a cookie with this prefix if it does not meet the following
- It must be marked with the
- It must be sent from a secure origin.
__Host- prefix is more restrictive and is thus preferable. In addition to the
requirements of the
__Secure- prefix, it must also meet these:
- It must not include the
- It must have its
Pathattribute set to
Always opt for the
__Host- prefix unless your application for some reason necessitates
the use of the
Domain attribute or setting the
Path attribute to something
other than the root. Proper use of prefixes helps prevent a man-in-the-middle (MITM) attacker from
overwriting cookie values.
Why should we use the HttpOnly attribute?
In case you're wondering, the name
HttpOnly does not mean "HTTP as opposed to HTTPS." Rather,
This helps prevent cross-site scripting (XSS) attacks.
Why should we use the SameSite attribute?
SameSite attribute controls whether a cookie is sent on cross-origin requests. There are
three possible values:
None(least secure): the cookie is sent on cross-origin requests.
Lax(intermediate security): the cookie is sent on cross-origin requests only if:
- the method is safe (
it is a top-level navigation (meaning the URL in the address bar changes),
as opposed to an AJAX request, a request from a
- the method is safe (
Strict(most secure): the cookie is not sent on any cross-origin requests.
Clearly, you should always use
Strict for your session cookies! Otherwise, you are leaving
yourself open to cross-site request forgery (CSRF).
Why should we use the Secure attribute?
Secure attribute ensures that the cookie is not sent unencrypted. It is only sent
over the HTTPS protocol. This helps to mitigate man-in-the-middle attacks.
Prefixing the session cookie in Laravel
To secure the session cookie, open up
config/session.php. The sections of interest to us
begin on line 118 (as of Laravel 8.57.0).
Let's make sure we understand what this code does:
It checks your
.envfile for a
SESSION_COOKIEvalue. If it finds one, it uses that, and does not proceed with the following steps.
It determines the name of your application by checking your
.envfile for an
APP_NAMEvalue. If no value is found, it defaults to
Using the application name determined in step 2, it constructs the cookie name using the
It may be tempting to modify this file directly. For example, you might want to just hard code the cookie name like this:
But I would recommend against this. If you develop locally using
php artisan serve,
it will work, because Firefox and Chrome make developers' lives easier by ignoring cookie
http://localhost. However, it is not future-proof. If one day you
switch to developing on a server on your network without HTTPS, then suddenly your cookies will
no longer work in development.
A more future-proof solution is to use environment variables as the framework developers intended.
.env files, add a new line under the other session-related variables. That way
you can exclude the prefix in development and include it in local/production.
Adding the Secure attribute to the session cookie in Laravel
Scroll down until you find the following:
This checks your
.env file for an environment variable called
SESSION_SECURE_COOKIE value. By default, it doesn't exist. So add it:
If developing on a server without HTTPS, you can set it to false in your development
Adding the HttpOnly attribute to the session cookie in Laravel
Keep scrolling until you get to this section:
Here we don't need to worry about
to access the session cookie, regardless of environment. So simply hard code it to
Adding the SameSite attribute to the session cookie in Laravel
Finally, scroll down to the bottom of the file.
Again, no need to worry about
.env files here. Hard code it to
And just like that, your session cookie is now secure. Don't forget to run
php artisan config:clear so that your changes take effect. Also double check that for
every change made to your local/development environment file, you also made the corresponding change
to the production file!
Understanding the CSRF cookie in Laravel
The CSRF token cookie is a little different. In my applications, I tend to remove this cookie
altogether. I do this because I like it when vulnerability scans find nothing wrong, but with
this cookie you cannot prefix it or add the
HttpOnly attribute without totally defeating
prefix it, you have changed the name, so the frameworks will probably miss it. If you add the
the potential vulnerabilities or remove it altogether. I opt to remove it.
According to the official Laravel documentation:
Laravel stores the current CSRF token in an encrypted
XSRF-TOKEN cookie that is
included with each response generated by the framework. You can use the cookie value to set the
X-XSRF-TOKEN request header.
libraries, like Angular and Axios, automatically place its value in the
header on same-origin requests.
Removing the CSRF cookie in Laravel
Removing this cookie is incredibly easy. Open up
By default, it looks something like this:
The parent class contains a
$addHttpCookie, which we need
to override and set to
That's all there is to it.
If you've ever applied to a web development position, then you've probably been asked to define MVC.
My answer usually goes something like this:
- M is for model. That's your data layer. A model is a class that allows you to interact with the data source and perform CRUD operations. Most often the data source is a MySQL database, but ideally the framework will provide support for different types of data sources.
- V is for view. This is a type of UI layer. It's the page that is displayed to the end user.
- C is for controller. This is also a type of UI layer. It is responsible for receiving a request and returning a response. That is, it returns the appropriate view based on the path of the request (the URL to which the user navigated) and possibly input such as form data. It is considered a best practice to keep your controllers as lean as possible. So your controllers should be relatively devoid of business logic, which should be handled in its own layer. A common approach is to put business logic in "service" classes (e.g. SaleHandler).
Obviously I think this is a good definition, otherwise I wouldn't give it in an interview! It's not as concise as it could be, but an interviewer is probably looking for evidence that you have an experiential familiarity with the concepts, as opposed to a regurgitation of a textbook definition. To illustrate, consider the hyper-generalized definition offered by Wikipedia :
Model–view–controller (usually known as MVC) is a software design pattern commonly used for developing user interfaces that divide the related program logic into three interconnected elements. This is done to separate internal representations of information from the ways information is presented to and accepted from the user.
Is it technically correct? Sure, but it's so vague that anyone not already familiar with MVC will probably have trouble visualizing how it would actually be put into practice. It doesn't even describe the components. If you gave this definition in an interview, the interviewer would no doubt ask you to elaborate.
Lately I have been reading Design Patterns: Elements of Reusable Object-Oriented Software and in the introduction, the "Gang of Four" (as the authors are lovingly called) use MVC as an example to elucidate what they mean by the term "pattern." Here is their definition:
MVC consists of three kinds of objects. The Model is the application object, the View is its screen presentation, and the Controller defines the way the user interface reacts to user input. Before MVC, user interface designs tended to lump these objects together. MVC decouples them to increase flexibility and reuse.
It occurred to me that you could really impress an interviewer if you gave them a canonical definition of MVC. I thought it reasonable to assume that this book's definition of MVC is the canonical one, because it's basically The Bible of The Church of Object-Oriented Programming.
For bonus points, you could even describe the components and their relationships in terms of other design patterns:
The model communicates with its views when its values change, and the views communicate with the model to access these values... [This] design is applicable to a more general problem: decoupling objects so that changes to one can affect any number of others without requiring the changed object to know details of the others. This more general design is described by the Observer design pattern...
MVC supports nested views with the CompositeView class, a subclass of View. CompositeView objects act just like View objects; a composite view can be used wherever a view can be used, but it also contains and manages nested views... [This] design is applicable to a more general problem, which occurs whenever we want to group objects and treat the group like an individual object. This more general design is described by the Composite design pattern...
A view uses an instance of a Controller subclass to impelement a particular response strategy; to implement a different strategy, simply replace the insance with a different kind of controller... The View-Controller relationship is an example of the Strategy design pattern...
MVC uses other design patterns, such a Factory Method to specify the default controller class for a view and Decorator to add scrolling to a view. But the main relationships in MVC are given by the Observer, Composite, and Strategy design patterns.
But have we arrived at a canonical definition? I did some digging and it turns out that Design Patterns, written in 1994, is not the first publication to define MVC.
Wikipedia has this to say about the history of MVC:
One of the seminal insights in the early development of graphical user interfaces, MVC became one of the first approaches to describe and implement software constructs in terms of their responsibilities. Trygve Reenskaug introduced MVC into Smalltalk-79 while visiting the Xerox Palo Alto Research Center (PARC) in the 1970s. In the 1980s, Jim Althoff and others implemented a version of MVC for the Smalltalk-80 class library. Only later did a 1988 article in The Journal of Object Technology (JOT) express MVC as a general concept.
This would seem to suggest that the first written publication to define MVC is that 1988 article in the Journal of Object Technology , which says this:
Model-View-Controller (MVC) programming is the application of [a] three-way factoring, whereby objects of different classes take over the operations related to the application domain (the model), the display of the application's state (the view), and the user interaction with the model and the view (the controller).
However, upon even further digging (i.e. going to the sources used by the Wikipedia article), I discovered that there is a publicly available note by Trygve Reenskaug (the Nowegian computer scientist whom Wikipedia seems to credit as the inventor of MVC) dating back to 1979! In December of that year, he wrote:
Models represent knowledge. A model could be a single object (rather uninteresting), or it could be some structure of objects...
A view is a (visual) representation of its model. It would ordinarily highlight certain attributes of the model and suppress others. It is thus acting as a presentation filter...
A controller is the link between a user and the system. It provides the user with input by arranging for relevant views to present themselves in appropriate places on the screen. It provides means for user output by presenting the user with menus or other means of giving commands and data. The controller receives such user output, translates it into the appropriate messages and pass these messages on to one or more of the views.
But wait, there's more! On one of his pages hosted by the University of Oslo, Reenskaug writes that "the hardest part was to hit upon good names for the different architectural components." Before he arrived at "Models-Views-Controllers," he was calling it "Thing-Model-View-Editor." In a note from May 1979, Reenskaug describes this prototype of MVC architecture:
[A Thing is] something that is of interest to the user. It could be concrete, like a house or an integrated circuit. It could be abstract, like a new idea or opinions about a paper. It could be a whole, like a computer, or a part, like a circuit element...
A Model is an active representation of an abstraction in the form of data in a computing system...
To any given Model there is attached one or more Views, each View being capable of showing one or more pictorial representations of the Model on the screen and on hardcopy. A View is also able to perform such operations upon the Model that is reasonabely associated with that View...
An Editor is an interface between a user and one or more views. It provides the user with a suitable command system, for example in the form of menus that may change dynamically according to the current context. It provides the Views with the necessary coordination and command messages...
So, have we arrived at the canonical definition? I will leave that for the reader to decide. I think we have probably arrived at the earliest definition ever given, but whether that is the best candidate for the definition is up for debate.
This morning I read Part II of The Autobiography of Benjamin Franklin. I discovered that in his quest for self-improvement Franklin employed a method of self-tracking similar to one that I use.
Franklin’s goal was to live in accordance with the following virtues:
He kept track of his progress using a table with seven columns (one for each day of the week) and thirteen rows (one for each virtue).
Several years ago, I began experimenting with a similar method of self-tracking. Like Franklin’s, my table has one column for each day of the week. However, in my table the rows represent not virtues but goals. One goal might be to write one page per day. If I fail to write one page on Monday, then I put a red X in that cell. If I succeed, then I put a green checkmark.
This method is simple yet powerful. By writing down your goals, you hold yourself accountable. By keeping a written record of your behavior over time, you become aware of larger-scale patterns that would otherwise elude you. Having a more accurate picture of yourself, you are better positioned to improve yourself.
If you google “do we know what electricity is,” you’ll find that someone asked the following question on Quora :
Why do some people say "We really don't know what electricity is." We have Maxwell's equations and we know that conductors have free electrons in their outer shells. So where does this belief come from?
The first reply:
There are a host of reasons why someone might say “We really don’t know what electricity is.” Some of them are philosophical, some of them are contrarian, some of them are deliberately misleading, and others come from a place of ignorance … Of all theories, none is more fundamental than the modern theory of electricity (QED) and none has shown better agreement between prediction and experiment.
This answer misses the point. When people ask if we really know what electricity is, they are not questioning the predictive power of quantum electrodynamics. It is obvious that scientists and engineers know how electricity works; if they didn’t, we wouldn’t be enjoying the benefits of electricity. But knowing how to manipulate something to achieve desired results is not the same as knowing what it is. The textbook definitions of electricity, being circular, do not satisfy someone seeking to form an understanding of what electricity is.
William Beaty, an electrical engineer, writes:
If we look up "electric charge" in a dictionary, we encounter a problem. The definition of "charge" is circular. What is charge? It's the stuff that causes electrical phenomena. What are electrical phenomena? Those are the things caused by charge! Simple, no? (grin!)
Brian Skinner, a physicist, writes:
If you ask a teacher “what is electricity?”, the standard answer you’ll get is that “electricity is the movement of electrons.” … [One problem with this answer] is that if you’re going to tell someone “electricity is the movement of electrons,” then you should probably tell the person what an electron is. And it turns out that science struggles to give a satisfying answer to even this obvious question.
For any science student at the college level or below, an electron is always drawn as a black dot and we are told that this black dot has a mysterious property called “charge”. The existence of such charged black dots is supposed to be taken as a given, with no explanation as to where they come from or what they’re made of.
If you happen to keep pursuing such questions to the level of graduate coursework in physics, the buck gets passed one level further, and you are told that an electron is actually a kind of excitation or defect in a pervasive, “electron field” that fills all of space. But don’t try to ask “what is this field?” or “what is it made of?”. You are likely to be told that such questions are nonsensical, and the electron field is simply a mathematical object.
So, if you’re keeping score, after just two levels of drilling into the question “what is electricity?” we arrive at the answer “it is a mathematical object.” Only a strange kind of person would consider that to be a satisfying form of understanding.
So what is electricity? My favorite explanation is given by Beaty:
There is a good reason why the definition of "charge" is circular. Like mass, length, and time, Electric Charge is a "fundamental." Many dictionaries say this: "Electric charge: a fundamental property of matter." … The circular definition is hard to avoid because normal definitions are based upon deeper concepts, and when we finally arrive at the deepest concepts of all, we cannot "take them apart" into their fundamental pieces … Electric charge is a component of atoms. In other words, after we have broken an object into molecules, and broken the molecules into atoms, when we break the atoms apart we discover particles of electric charge. Charge is material, it is like atoms but it is one step lower than atoms. Most science textbooks tell us that solid objects are made of atoms. It is also valid to state that solid objects are made of electric charge. Objects are made of equal quantities of positive and negative charge, and objects stay together because of the attraction between the quantities of opposite charge inside them. Chemical bonds are electrical in nature.
I am satisfied when Beaty says that "objects stay together because of the attraction between the quantities of opposite charge inside them." I can think of electricity as the reason my body stays together.
I find it helpful to remember that there are four fundamental interactions in nature (“interactions that do not appear to be reducible to more basic interactions”):
- The weak interaction
- The strong interaction
Reality consists of stuff. Stuff is made up of specific kinds of particles (e.g. electrons) that interact with each other in specific ways (e.g. electromagnetism). To dive any deeper we have to ask: Why is reality structured this way, as opposed to some other way? That is another question altogether!