asp.net Web Api custom authentication requirement

2019-09-18 14:40发布

问题:

Please provide your feedback on my solution against following requirements.

Requirement (similar to):

1.a let say that authentication Token is made out of the Email and date and is encrypted

1.b authentication Token is send back to the client through header

1.c authentication Token is stored on client and server

My solution :

1) To send authentication Token back to the client through header. i have used cookie, and following code.

  HttpCookie cookie = new HttpCookie("AuthenticationToken");
      cookie.Value = "EncryptedToken";
      Response.Cookies.Add(cookie);

2) I will store authentication Token in database, and for each request i compare token saved in cookie with token stored in database. (assume that encrypt,decrypt operations are done properly )

Your feedback/commments?

回答1:

It looks to me OK. However, if you are encrypting (so you can decrypt back) and can find out email (identifying user) and time token issued (hence verify whether expired or not), do you still need to store it in database? I would, only if i had other requirements such tracking, etc.



回答2:

I have no expert knowledge in security. To me your idea sounds doable.

However, I was curious why you wanted to do "custom" authentication like this? Have you taken a look at "build it" ASP.NET authentication done in Web.API?

Then you could create a custom HttpOperationHandler using standard .net stuff like:

var ticket = FormsAuthentication.Decrypt(val);
var ident = new FormsIdentity(ticket);
...
var principle = new GenericPrincipal(identity, new string[0]);
Thread.CurrentPrincipal = principle;
...
if (!principal.Identity.IsAuthenticated)
    return false;

Also, you might want to read about Thread.CurrentPrincipal and Current.User

The pro is that you don't need to store authentication token in some DB on the server and retrieve it on every request.