skip to Main Content

I’m writing a web application using C#, ASP.NET, jQuery and using forms authentication:

<authentication mode="Forms">
  <forms loginUrl="Account/Login.aspx" defaultUrl="Default.aspx" name=".ASPXFORMSAUTH" timeout="30" />
</authentication>
<authorization>
  <deny users="?" />
</authorization>

The application is a command & control that designed to be open for a long time, using SignalR for receiving data from the server and jQuery ajax for sending data.
I want the user to enter his credentials if he refreshed the page (F5), so the authentication ticket timeout is set to a minimum of 1 minute only, in the login.aspx.cs:

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(userFullName, false, 1);
string hashedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashedTicket);
Response.Cookies.Add(httpCookie);
string returnUrl = Request.QueryString["ReturnUrl"];
if (returnUrl == null)
    returnUrl = "~/Default.aspx";
Response.Redirect(returnUrl);

The problem is that after 1 minute, every jQuery post request is rejected, with the error message:

Failed to load resource: the server responded with a status of 401 (Unauthorized)

Should I incorporate any authentication data in the post request?
Any other solutions?

2

Answers


  1. Chosen as BEST ANSWER

    I've solved it by adding another aspx page, which holds all the web methods.
    All of the jQuery post requests were diverted to this new page.
    I've added the following to the web.config file:

    <location path="DataResponsePage.aspx">
      <system.web>
        <authorization>
          <allow users="*"/>
        </authorization>
      </system.web>
    </location>
    

  2. Before executing the post to the server with your form you must execute a query with the backend to verify if your user is authorized or not. If not, you need to ask the user again for the credentials.
    So that you don’t have to ask for new credentials all the time you can use a refresh token. Do a search on "refresh tokens".
    Another solution since you are using asp.net is to use the microsoft.identity package, it will take care of all the authentication for you and you can define how long the user login is valid. I strongly recommend that you use it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search