How to pick up an existing cookie via javascript

Asked

Viewed 1,459 times

0

In my project I have a page that is html. And since my project is in Asp.net mvc, I can’t validate whether the user is logged in or not because this page is not Razor.

Researching, I found the javascript cookie, that creates, reads and deletes cookies. So basically, I already have one cookie created and what I wanted was that the javascript cookie take that cookie make a validation to see if there is a cookie, if not, redirect to the login.

So far I have this code:

  <script>
    function getCookie(cname) {
        var name = cname + "=";
        var ca = window.document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1);
            if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
        }
        return "";
    }
    function checkCookie() {
        var permissao = getCookie(".PermissionCookie");
        if (permissao == "") {
            alert("Oooops! Você não tem permissão!");
            window.location.replace("/Index/Autenticacao")

        }
    }

</script>

But it’s not working...

Remembering that I want this check to be done as soon as the page loads.

What can I do to make it work ?

  • It’s not working because it’s not getting the cookie you already have in the application. I don’t know why the page is in html. Except by ajax.I’m calling it on an existing button on the page. Only when it’s clicked nothing happens.

  • Do you have access to the code of the website you want to check logged in? I could not make an AJAX/REST request through javascript by returning true/false?

  • @mgibsonbr that very thing. I wish you would not access the page if you are not logged in, and rodrigopq if by ajax you can do this kind of checking, for me would be great! What matters to me is: if you are not logged in, do not have access to this html page.

  • I can’t reproduce your problem... http://jsfiddle.net/mgibsonbr/xzn05t26/ See if the cookie really is not there, and if the button you are clicking on the page is actually calling the desired code.

  • @mgibsonbr explaining: I have an authentication action. And in it I bake a cookie with the permissions and the user id. So on Azor pages, I can do this check of what’s in the cookie and show the user only what they can access. But on HTML pages I can not do this cookie check by code c# the same as on the Razor pages. Or if you do this with javascript, or ajax, if it can actually be used.

  • So what I want to do is the following: when loading the page, javascript checks for me if there is any cookie generated, that is, if there are any users logged in to the application. And if IN CASE NO USER IS LOGGED IN, do not let enter the page, redirecting to a login screen, I already have here. It’s become clearer now ?

  • Okaaay. Let me see here. And I warn you! And trying here on your fiddle. He gives that I don’t have permission. That’s what I want.

  • Now I have another problem... Even the logged-in user can’t get the cookie. And it keeps redirecting. (. Seeing on the console it shows that the cookie has nothing. Ie: "". The way you return in the getcookie function.

  • I cannot see it in the browser console. The only thing that appears is: [""]. That is, what the getcookie function returns. :(

  • Yeah, we’re getting somewhere... :) I’m not sure, but this could be the result of a cookie HttpOnly - which is exchanged between the server and the browser, but which Javascript does not access. This could make cookies look empty. Now it’s already a matter of ASP.NET - which I know nothing about - so I’m afraid someone else will have to help you... :(

  • @mgibsonbr would using AJAX solve my problem ? If yes, you know how to use ?

  • The client part, yes, the server part, no. @rodrigogq would like to answer something?

  • @Does Erikthiago really need to be HTML? Isn’t it possible to do a simple php at least? It’s not very safe to do what you’re doing. The easiest thing would be to file a requisition $.get() by jquery, but just be a programmer to get that portion out of the code and ready, the page is visible.

  • Worse than it is. Because if I do it the normal way by Asp.net mvc , that is, doing cshtml, it doesn’t work, because a cshtml page needs to have an action from which to take all the logic. Unless that page is a partial. But I haven’t tried yet. And even, it would have to be a cshtml...

Show 9 more comments

1 answer

1


To make an AJAX jquery request, create a "checkAccess.js" file, or something like and put it in the include of your page.

 $(document).ready(function(){
   $.get("http://www.seusite.com.br/pagina.asp", function(data, status){
     alert("Data: " + data + "\nStatus: " + status);
   });
 });

On this page of yours, you replace the Page_Load by a Response.Write with true/false (even a string) and ready:

 string json = "{\"logado\":\"true\"}";
 Response.Clear();
 Response.ContentType = "application/json; charset=utf-8";
 Response.Write(json);
 Response.End();

Cookies seem a little complicated to me. You can even remove some of them, but I think the internet explorer will be warning that your site has an Activex component (javascript) trying to do something suspicious. I don’t remember which versions, but if the user does not accept, your javascript will be useless.

Already the jquery is better.

If the session is falling (the guy is spending too much time on multiple HTML pages) and is dropping, it is best to put one <img href="http://www.seusite.com.br/img.gif" /> with a 1px gif per 1px transparent... this should be enough to keep the session active.

I still find it very unsafe, but I don’t know what the status of your project as a whole.

  • Logically you won’t give the alert, but will take the necessary action when you are logged in... or undone! Try to leave your entire page hidden and only give one show when you’re sure it’s okay.

  • in this string json ai, I would put in a javascript block ? And it’s quiet. My system does not have sensitive information no.

  • Yes, exactly. In case I put a variable call logado. There in your jquery, in place of the alert, you can do a type check if(data.logado) { ... } else { ... }.

  • Got it. So I can only do if. Then it would be like: if(date.logged in == null){here oredirect to login page}. Because if the user is logged in, they don’t even do it. Right ?

  • On your ASP page you can check if it is logged in and return the string true if yes, or false if not. In jquery you only check by true same, that’s when it works. In Else you redirect to log in.

  • dude, it didn’t work. :(

  • Which part did not work? You can give more details?

  • Does not recognize the Part of the Answer. :(

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.