locked
Authenticate POST and PATCH calls in ASP.NET Web API RRS feed

  • Question

  • User-1489021858 posted

    Web API should be RESTful, but I need to authenticate the calls. Anyone can send REST calls from their browser to my server and I have to make sure that they are logged in (have a sesson cookie) and that they have access to the object they try to read and write to.

    I have followed the steps in this article:

      https://www.strathweb.com/2012/11/adding-session-support-to-asp-net-web-api/

    It works well for GET calls. But I still don't get any information about session or context in POST and PATCH calls. In fact I find that:

       HttpContext.Current == NULL

    How to solve?

    ( I can't believe this isn't a major issue for anyone dealing with REST calls and login-protected data.)

     

    Friday, August 4, 2017 2:55 PM

All replies

  • User753101303 posted

    Hi,

    Bad async usage maybe ? At which point in your code do you find that HttContext.Current is null?

    Also don't confuse session and authentication ("session" is a bit overloaded, the article talks about session variables not about an authenticated user session) which are not directly related. You are callling this from a server browser or from another server ? The basic idea is that this is just http and you could use the same authentication options than for any other http request.

    Friday, August 4, 2017 3:27 PM
  • User475983607 posted

    Also, you can learn about securing Web API at the following link.

    https://www.asp.net/web-api/overview/security

    Friday, August 4, 2017 3:50 PM
  • User-271186128 posted

    hi 

    But I still don't get any information about session or context in POST and PATCH calls. In fact I find that:

       HttpContext.Current == NULL

    How to solve?

    AFAIK, HttpContext is only available when there is a request that is being processed , in the case of a session timeout, there is no active request and therefore you can't use HttpContext.Current. You could check the following links:

    http://stackoverflow.com/questions/464456/httpcontext-current-session-vs-global-asax-this-session .

    http://stackoverflow.com/questions/27657773/why-is-httpcontext-current-null-during-the-session-end-event

    Besides, I have created a mvc project to login. The session stores login info. You could get information about current session in web api.

    Please refer to the following code:

    Code in model:

    public class SessionModel
        {
            public string UserName { get; set; }
            public string User_Pwd { get; set; }
            public string Session_Val { get; set; }
        }
    

    Code in MVC Controller:

    public ActionResult MySession()
            {
                return View();
            }
            [HttpPost]
            public ActionResult MySession(SessionModel info)
            {
                    Session["UserId"] = info.UserName;    //create session
                return RedirectToAction("UserSessionSection");
            }
            public ActionResult UserSessionSection()// show user info in session
            {
                var Data_session = new SessionModel();
                try
                {
                    if ((Object)Session["UserId"] != null)
                        Data_session.Session_Val = "Welcome  " + Session["UserId"].ToString();
                    else
                        Data_session.Session_Val = "Session has been expired";
                }
                catch
                {
                }
                return View(Data_session);
            }   
    

    Code in MySession.cshtml:

    @model WebMVC6.Models.SessionModel
    @{
        ViewBag.Title = "MySession";
    }
    
    <h2>MySession</h2>
            <legend>User Login </legend>
            @using (Html.BeginForm())
                {
                <table>
                    <tr>
                        <td align="right" ;>
                            User Name:
                        </td>
                        <td>
                            @Html.TextBoxFor(a => a.UserName)
                        </td>
                    </tr>
                    <tr>
                        <td align="right" ;>
                            User Password:
                        </td>
                        <td>
                            @Html.PasswordFor(a => a.User_Pwd)
                        </td>
                    </tr>
                    <tr>
                        <td></td>
                        <td align="right" ;>
                            <input id="btnLogin" type="submit" value="Login" />
                        </td>
                    </tr>
                </table>
            }
    

    Code in UserSessionSection.cshtml:

    @model WebMVC6.Models.SessionModel
    @{
        ViewBag.Title = "UserSessionSection";
    }
    <script>
        function getSession() {
            var apiBaseUrl = 'http://localhost:54996';//change to your url
            $.ajax({
                type: "POST",
                url: apiBaseUrl + '/api/values',
                success: function (data) {
                    alert(data);
                }
            });
        }
    </script>
    <h2>UserSessionSection</h2>
        <h4>
            @Html.DisplayFor(a => a.Session_Val)
        </h4>
    <input type="button" value="GetSession" onclick="getSession()"/>
    

    Code in Api Controller:

           [HttpPost]
            public string Post()
            {
                var session = HttpContext.Current.Session["UserId"];//get session
                if (session != null)
                {
                   var info= session.ToString(); z
                    return "Get sessionID:"+info;
                }
                return "Session is not availabe ";
            }
    

    Code in WebApiConfig.cs:

    public static class WebApiConfig
        {
            public static string UrlPrefix { get { return "api"; } }
            public static string UrlPrefixRelative { get { return "~/api"; } }
            public static void Register(HttpConfiguration config)
            {
               config.MapHttpAttributeRoutes();
                config.Routes.MapHttpRoute(
                 name: "DefaultApi",
                 routeTemplate: WebApiConfig.UrlPrefix + "/{controller}/{id}",
                 defaults: new { id = RouteParameter.Optional }
             );
            }
    }
    

    Code in Global.asax.cs:

    //add the following code to support web api in mvc project
    GlobalConfiguration.Configure(WebApiConfig.Register);
    // add the following code to get current session
    protected void Application_PostAuthorizeRequest()
            {
                if (IsWebApiRequest())
                {
                    //could get current session
                    HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
                }
            }
            private bool IsWebApiRequest()
            {
                return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith(WebApiConfig.UrlPrefixRelative);
            }
    

    You could get current session like this:

    Best regards,
    Dillion

    Tuesday, August 8, 2017 9:22 AM