14

Why is the Web Security is working differently on different browser:

Details:

I have two applications

One is a simple HTML application and another one is an ASP.NET MVC4 WebApi application and the projects are inside of same solution and i have set multiple start-up project for run the application for same time .


Working version:

I have Used Web Security in the Web API project. I did full implementation of web security...

Login Action Code

// GET api/company
[System.Web.Http.AcceptVerbs("Post")]
[System.Web.Http.HttpPost]
public HttpResponseMessage Login(LoginRequest loginRequest)
{
    try
    {
        if (WebSecurity.Login(loginRequest.EmailAddress, loginRequest.Password, true))
        {
            var userDetails = new string[2];
            userDetails[0] = loginRequest.EmailAddress;
            var currentUSerRole = Roles.GetRolesForUser(loginRequest.EmailAddress);
            userDetails[1] = currentUSerRole[0].ToString();
            HttpResponseMessage response =
                Request.CreateResponse(HttpStatusCode.Accepted, userDetails);
            return response;
        }
        else
        {
            HttpResponseMessage response
                = Request.CreateResponse(HttpStatusCode.Unauthorized);
            return response;
        }
    }
    catch (Exception e)
    {
            HttpResponseMessage response
            = Request.CreateResponse(HttpStatusCode.Unauthorized);
           return response;
    }  
}

*WebSecurity.Login* is working on all browsers when i call the login method using Ajax. But I have another method in another controller, That named as CurrentDateAndUser

Code:

[AllowAnonymous]
[System.Web.Http.AcceptVerbs("Get")]
[System.Web.Http.HttpGet]
public HttpResponseMessage CurrentDateAndUser()
{
    if (WebSecurity.IsAuthenticated)
    {
        int userId = WebSecurity.CurrentUserId;
        string[] currentDateAndUSerId = new string[2];
        currentDateAndUSerId[0] = userId.ToString();
        currentDateAndUSerId[1] = DateTime.UtcNow.ToString();

        HttpResponseMessage response =
            Request.CreateResponse(HttpStatusCode.Accepted, currentDateAndUSerId);
        return response;
    }
    HttpResponseMessage responseNew =
        Request.CreateResponse(HttpStatusCode.NotAcceptable);
    return responseNew;
}

Issue:

  • If I call the CurrentDateAndUser method from Microsoft Internet Explorer Using an Ajax call, then everything works. The WebSecurity.IsAuthenticated returns true and is working well.

However,

  • If I call the CurrentDateAndUser method from Google Chrome Or Mozilla Firefox using an Ajax call, then nothing works. The WebSecurity.IsAuthenticated always returns false.

I don't know why. If you have any idea, then please let me know.


I also found a similar problem (not sure if it is a real issue):

When I run my application with Fiddler, I see a different result:

When i call the CurrentDateAndUser method from IE, the request is:

enter image description here

I can see the Cooke/Login values in above image


But When i call the CurrentDateAndUser method from Chrome And Firefox , the request is:

enter image description here

I can't see the cookie values, meaning that the Web Security.IsAuthenticated property is returning false.



Is it Bug in WebSecurity?????


Edit

My Ajax request code is

function GetCurrentUserId() { 
    return $.ajax({
        method: 'GET',
        url: rootUrl + '/api/Common/CurrentDateAndUser',
        async: false
    }).success(function (response) {
        return response[0];

    }).error(function () {
        toastr.error('Somthing is wrong', 'Error');
    })
}

This request does not send the Auth Cookie values to Web API method when I run the application in Chrome and Firefox, however, this request sends the cookie values to the API method, if it is run in IE

i have posted the Image , Please take a look at the above image

  • probably you just need to send the HttpStatusCode.Unauthorized on the second case to make the browser login again. – Pedro.The.Kid May 06 '14 at 14:18
  • I also tried. It is nothing worked. I think i have a any cors issue, but i can't get solution yet. f**King issue.. –  May 13 '14 at 09:31
  • call your application with fiddler to see what happens on firefox and chrome. you should see a 401 code. if you get a 401 and no prompt for user name its a bug on the browser if the code is different from 401 you are overwriting the response. normally you should see two 401 followed by a 2** or 3** response. – Pedro.The.Kid May 13 '14 at 10:30
  • PS: I'm assuming you changed the CurrentDateAndUser to on error reply with HttpStatusCode.Unauthorized – Pedro.The.Kid May 13 '14 at 10:38
  • Why are the ports number different (50949 vs 12345)? And see answer to this question (read what they say about IE behavior): http://stackoverflow.com/questions/1612177/are-http-cookies-port-specific – Salman A May 20 '14 at 09:09

3 Answers3

2

The issue is not with web security at all, it's with the way you implement your security. You should never be using a userid, email, or anything important in the cookies.

I would suggest you use the FormsAuthentication class to encrypt and decrypt your cookies, and even so, only store something such as the SessionID plus a custom hash of that session ID to verify your self when you decrypt the cookie

Here is a site that gives a pretty good example: http://www.c-sharpcorner.com/uploadfile/nipuntomar/update-formsauthenticationticket/

Dan
  • 734
  • 1
  • 9
  • 23
  • Thanks! Please see my question one more time, i have edit my question. and explain little more –  Apr 30 '14 at 12:22
  • +1 I agree your answer. But it's why working in IE? but why it does not working in Chrome and FireFox? –  Apr 30 '14 at 12:26
  • 1
    I've been looking around, but I'm not quite sure why IE would, and Firefox/Chrome wouldn't. It could be related to IE settings allowing more access since you're hosting/debugging locally. Try hosting it on a remote site and see if IE still sends the cookie? Here's another link that may help: http://stackoverflow.com/questions/7911710/jquery-ajax-call-not-sending-cookie – Dan Apr 30 '14 at 12:34
  • I like this link, I will try that –  Apr 30 '14 at 12:38
0

There are 3 things around it:

WebSecurity.IsAuthenticated actually returns the value of HttpRequest.IsAuthenticated, which is true if the Forms Authentication cookie has been set and is current. It's not available until the user makes the next request after successfully logging in, which is why you are seeing the behaviour that you describe.

I remember reading on MSDN or someplace, the WebSecurity.IsAuthenticated does not work until the page is fully loaded. Meaning if you login a user in a page and in the same flow of code you check IsAuthenticated, it will NOT return True. For IsAuthenticated to be True the page has to be reloaded or use the better practice; which is to redirect the user to another secured page as soon as the login is successful and in that page check IsAuthenticated.

We had the same issue with Chrome (version 21.0.1180). Despite that we see expiration date on Header, some Chrome in Windows XP ignored it. Then we removed the Expiration Date and Chrome accepted keep the session cookie without problems.

So what to do is: After login try to check this on new page not on same page.

Also try to set cookie explicitly

System.Web.Security.FormsAuthentication.SetAuthCookie(user.Username, false);
Nipun Ambastha
  • 2,553
  • 1
  • 16
  • 26
  • The first paragraph form asp.net website and the second one is from this stack overflow website and third one is support chrome website. I already read all. I thing you miss understand my question. My problem is the ajax method does not send auth cookies when i run the application from Chrome and FirFox. does make sense dude? –  Apr 30 '14 at 12:16
  • Thanks! Please see my question onemore time, i have edit my question. and explain little more –  Apr 30 '14 at 12:22
  • Is it any domain issue? \ –  May 02 '14 at 08:49
  • Did you try on different machine? – Nipun Ambastha May 02 '14 at 10:08
  • Yes, I tried it on different machines. Same problem. –  May 02 '14 at 10:12
  • Did you try removing email address from cookie? – Nipun Ambastha May 02 '14 at 10:47
  • NO! Actually I found a problem. the request header haven't any cookies if i call the web api method using ajax from chrome browser. But i can see the header cookie when i run my app in IE browser. So now i want to how to access the current cookies from client side to server side via request header??? –  May 02 '14 at 10:50
  • Lets get back to basics, forget current issue and try out new project just to implement this: first start with Form authentication http://www.asp.net/web-forms/tutorials/security/introduction/forms-authentication-configuration-and-advanced-topics-cs – Nipun Ambastha May 02 '14 at 10:59
  • http://stackoverflow.com/questions/15853237/user-identity-isauthenticated-vs-websecurity-isauthenticated As you see IsAuthenticated is just a wrapper. – Nipun Ambastha May 02 '14 at 11:01
  • oops! That's not helps to me. I also tried both ways. but same result. the ...ISAuthenticated always return false if ran my application on chrome and firefox. very strange –  May 02 '14 at 11:08
0

I don't know if this will help or not.

But I remember I was learning jQuery ajax So I setup a simple project on my laptop. When I tested it, it worked fine on IE, but failed in Chrome. After searching for hours, I found that Chrome will not allow AJAX requests from the local machine. When I tested it using an actual web server it worked fine for IE and Chrome.

So my question and advice is: are you testing on the same machine? Try to deploy it to a machine running a web server with a unique domain name and test your application!

tew
  • 2,723
  • 5
  • 23
  • 35
stackunderflow
  • 3,811
  • 5
  • 31
  • 43
  • `are u testing on the same machine`?? Yes. I will try that dude. –  May 13 '14 at 11:37
  • Plz deploy to a remote server and test your browser's and give us the feedback – stackunderflow May 13 '14 at 11:48
  • And one more test to confirm this hypothesis, is try to test Ajax with any simple project that doesn't involve security and see how browser's respond on the same machine, and how they respond on real websites – stackunderflow May 13 '14 at 11:54