This is my second post on Spring Security (first being this) and I will try to be more detailed here. Please keep sharing your feedback with me so that I could improve myself.
After all of the lengthy setups, primary value that we get from Spring Security (or any other security framework) is the ability to authenticate and authorize each request that application receives. First I will try to explain a bit the processes of authentication and authorization.
In almost every webapp, there are some pages (or resources) available for everyone, while some other pages are available only for logged-in users. So if a user is not logged into the system and tries to request a secure page, usually you would want them to be redirected to login page. If they login successfully, you will redirect them back to the original page they requested.
It is quite possible that you maintain different authorities for different users in your system. For example, some of your secure pages are requestable by every loggedin user, but you have kept some other only for admin users. So whenever a logged-in user requests a page, you will first verify if they have the authority to open this page. If yes, you will send them the page, otherwise you will redirect them to another page which will tell them that the requested page is forbidden for them.
Normal Non-AJAX Requests
Authenticating and authorizing normal (non-AJAX) requests is a pretty straight forward task and can be achieved with very little configuration. However it is out of scope of current post.
Authenticating and authorizing AJAX requests is also a simple task, however it requires bit deeper understanding of the framework. Before we jump into the implementation, let’s first define desired behavior when AJAX requests are authenticated and authorized.
When authentication fails for an AJAX request, you cannot redirect the user to the login page (at least from within the server). Therefore, if such thing happens, we would like to show user an alert message telling them that they need to login before they could send this AJAX request. For their convenience, we could add a “Redirect to login” button in the alert box which could save them a few clicks.
Similarly, authorization failure of an AJAX request should open a popup telling user that they do not have enough privileges to request current resource.
To achieve this behavior, we will need to write some code for both server-side and client-side: