简体   繁体   中英

How to check if user is authenticated in Web API 2

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.

I do this in the following steps:

  1. User calls Login and gets back an access token guid and an expiry timestamp.
  2. User adds a request header to subsequent calls with the access token.
  3. I check the access token is still valid / hasn't exceeded quotas, and that the request originates from the same IP as the original Login, and if ok, authorise it. I do this using a custom AuthorizationFilterAttribute, which I can decorate my API methods with easily.
  4. I extend the expiry on a successful call.

Hope this is clear.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM