Some areas of my SPA need to be open to all users, and some areas require authentication. In these areas, it's the data loaded via AJAX that I want to protect.
I have an authentication service (see below), which I add as a dependency in my durandal main.js. The service is called:
authentication
In my main.js I call
authentication.handleUnauthorizedAjaxRequest(function () {
app.showMessage('You are not authorized, please login')
.then(function () {
router.navigateTo('#/user/login');
});
});
It warns the user they are not authorized, and navigates user to a login view/viewmodel where they can enter details and try logging in.
Some questions that come to mind when building this authentication viewModel:
- Are there any obvious concerns with what I'm doing?
- Is this how I'm 'meant' to do things in Durandal?
- Am I re-inventing the wheel? I couldn't see anything like this within Durandal.
Most people seem to be creating seperate cshtml pages; one for login (if the user is not authenticated), and the usual index.cshtml Is there any good reasons for me to switch to that method?
My login action on my the server-side 'user controller' has the [ValidateAntiForgeryToken] attribute I need to send that as well.
I also have an 'antiforgery' service (see below) which I also add as a dependency in my main.js viewModel file
then (also in my main.js).
antiforgery.addAntiForgeryTokenToAjaxRequests();
This intercepts all ajax requests (along with content), and adds the MVC AntiForgeryToken value to the data. Seems to work exactly as I want it to. Please let me know if there's any errors/mistakes.
Complete authentication service below.
// services/authentication.js