1

I have ASP.Net MVC5 site. There is a login view/page.

For validating user, I have an action in controlller. Now if user credentials are valid, I set a session variable.

Code Snippet

public ActionResult ValidateUser(string userName, string pwd)
{
   User dal = new User();
   bool flag = dal.Authenciate(userName,pwd);
   if(flag)
   {
      Session['userId'] = userName;
   }
   else
   {
      //user invalid
   }

   return View();

}

Now for Authenticated User, subsequent request the hit will go to WebApi Controller.

I am in need to access the Session['userId'] value in WebApi controller, but WebApi doesn't have anything Session as it stands on the REST principle.

Now my question is,What is the right way to handle this requiment?

WebApi Controller

 public IEnumerable<Course> Get()
    {
        int userId = Convert.ToInt32(Session['userId']);
        User dal = new User();
        IEnumerable<Course> courses= dal.GetCourses(userId);

        return courses;

    }
Kgn-web
  • 7,047
  • 24
  • 95
  • 161
  • If you can't access the session, you'll have to pass the user id in. –  Dec 29 '15 at 18:54
  • 1
    Will all requests come from the same browser (MVC and Web API)? If so, cookie based authentication implemented through forms based authentication would be an easy way to solve your authorization issues. Have a look here http://www.asp.net/web-api/overview/security/forms-authentication – Andre Kraemer Dec 29 '15 at 18:57
  • @Amy..my WebApi action will get called from JavaScript,alternate way that somewhere in browser I have to pass the userId while calling action of normal controller& store & then pass but I don't prefer to do that.. bcz I feel it as unsafe – Kgn-web Dec 29 '15 at 18:57
  • I'm on my phone or I'd give a better answer. Look at how to use tokens with Api authentication/authorization. – ohiodoug Dec 29 '15 at 18:58
  • @AndreKraemer.. Yes,. agreed that I can authenticate the action using `Authorize` attribute but I am in need to access the userId value & then pass it to DAL layer.. – Kgn-web Dec 29 '15 at 19:00
  • @ohiodoug..Yes..please do that..meanwhile I will check on how to use tokens with APi – Kgn-web Dec 29 '15 at 19:01
  • 2
    @Chetan both the apicontroller and the mvc controller should have a User property. If you are authenticated you can get the current user from it (https://msdn.microsoft.com/en-us/library/system.web.http.apicontroller.user(v=vs.118).aspx) and query for userid through the identity property https://msdn.microsoft.com/en-us/library/microsoft.aspnet.identity.identityextensions.getuserid(v=vs.108).aspx. However, going for token based authentication as proposed by ohiodoug would probably be a better way – Andre Kraemer Dec 29 '15 at 19:08
  • 1
    Check [this](http://stackoverflow.com/questions/28657852/how-to-get-user-context-during-web-api-calls). – BabyDuck Dec 30 '15 at 10:42
  • REST APIs should be stateless. – Matjaž Dec 30 '15 at 15:12

0 Answers0