Reputation: 5
I have a Web API 2 service. In ApiController I create some different methods. One of these methods is used for user Login. In this method I can check user name and password hash selected from DB, and if they are correct, I can generate SessionID for current user session identification. But when I call other method and trying to check generated in previous step SessionID, this ID is empty (null). How I can to save this SessionID and how I can check if user is already authenticated in service ? I don't want to select user name and password hash from DB on each new method call. I just want to store this information somewhere and have ability to read it in each ApiController method or somewhere else.
Upvotes: 0
Views: 2799
Reputation: 1657
I do this in the following steps:
Hope this is clear.
Upvotes: 1
Reputation: 1146
What you describe sounds like cookie-based authentication to me. For the you could take a look a ASP.NET Identity 2.0 which works (mostly) flawlessly with WebAPI 2.0.
In the standard setup (with forms login) ASP.NET Identity will create a session cookie containing proof of authentication so that no subsequent database calls are required. Additionally you get things like claims and roles for free and you can integrate with social authentication providers with very few LOCs! It plays very well with Entity Framework too, so if you already use that just go for Identity!
If you want to roll your own, you may want to serialize the "user-profile" to a cookie and sign it cryptographically in order to make it tamper-proof. Then a middleware just has to de-serialize it and to put it as User-identity into the request object (considering you are using OWIN)
Upvotes: 0