0

I am working on an application where certain actions are performed using ajax requests to a backend api page, such as adding likes to content. The javascript function will pass the user ID and content ID to the api page in an xmlhttp request.

We use Forms Authentication with Active Directory.

For obvious reasons, I want to verify that the input I receive on the api page before doing anything at all.

While my web.config makes sure that only logged in users can access the api page, I can't find any way to get the current user's info such as username. I tried the following:

Membership.GetUser().Username;

How do I go about getting the logged in users' information from my page?

thanks

Cas
  • 758
  • 14
  • 36

1 Answers1

0

HttpContext.Current.User returns an object of type IPrincipal, and IPrincipal.Identity returns an object of type IIdentity.

HttpContext.Current.User.Identity.Name gives you the username

HttpContext.Current.User.Identity.IsAuthenticated gives you the authentication status (boolean)

Armed with that, you can look up other details in the database, possibly storing them in the Session.

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
  • Thanks, I ended up using HttpContext.Current.User.Identity.Name To get the logged in user's username. Which I then use to get their ID from the database. – Cas Jun 15 '15 at 13:30
  • You're welcome. Imho you should try to avoid passing the user id from JavaScript if possible. Its totally unnecessary as you can get the user id by looking it up from the server-side authenticated username. What you are doing, checking the supplied id, is a reasonable second best though. More discussion here http://stackoverflow.com/a/30683127/397817 – Stephen Kennedy Jun 15 '15 at 13:34
  • Yeah I figured I could just as well just get it from the logged in users' info. I build the JS really quick as a proof of concept in a hurry and will surely improve it now that I know how to get the information for the current user. – Cas Jun 15 '15 at 13:36