btt
btt

Reputation: 422

How to handle SPA authentication to an ASP.NET MVC 5 back end without using Session?

I am currently developing a SPA application that uses only a couple of full Razor views. Any time I ask a Controller for data, I am checking a Session variable to see if the user is currently logged in and authorized. This "feels" right in a standard MVC/Webforms application, but not so much in an SPA when it comes to handling timeouts, etc.

Overall this is working fine, but I am wondering if there are any existing best practices or alternate ways to handle this basic situation? Just looking to learn! Thank you.

Upvotes: 2

Views: 1290

Answers (1)

cchamberlain
cchamberlain

Reputation: 17956

SPA's are moving away from session state (they are generally stateless, like http, and would rely on a web API and tokens). You would make a call to the api to get information about what to show on the client. I would highly recommend digging into JWT tokens (OAuth2 / OpenID) since they can be issued by a web api (authorization) server and decoded by the client. Pre-JWT the client would get an opaque token and just store it so that it could submit it back on each authorized request, but with JWT the token carries with it a lot of meaning that you can use to do things such as build your SPA interface. If the token has a claim of role type with value of Admin, then you know that the user is an admin and can show admin features in the SPA. Claims can be at the role level or as diced up as you need them to be.

Another good thing about JWT tokens is you don't need to store them on the server either. The server stores a secret that is used to sign the token when it is issued and it uses the secret to verify that a JWT token that is submitted to it is valid. The client could change the claims and send back a falsified token but the server would deny it based on it not signing correctly with the secret.

Any state you are tracking in session state that cannot be tracked via claims, I would just store in local storage / cookies on the client or in a database / redis style cache server side.

Highly recommend going through this guys series - http://bitoftech.net/2014/10/27/json-web-token-asp-net-web-api-2-jwt-owin-authorization-server/

Upvotes: 1

Related Questions