JavaScript无需登录即可阻止访问受限页面

时间:2017-10-24 19:20:44

标签: javascript jquery

登录到页面后我有一个登录页面我转到下一页(欢迎)。 问题是,如果我复制并粘贴下一页(欢迎)的URL我的页面也打开了,我想限制打开下一页没有登录访问权限。 指导我做什么。

脚本

function click() {
    inputname = $('#name').val();
    inputpassword =$('#pass').val();

    for (i in data.username )      //to match username with provided array
      { 
        name = data.username[i];

        for ( i in data.password){
            pass = data.password[i];

            if (inputname == name & inputpassword == pass ){
                window.open('welcome1.html','_self');
            }               
        }
    }

    if (inputname != name & inputpassword != pass ){
        alert("Wrong Password");
    }
}

HTML

<input type="mail" id="name">
<input type="password" id="pass">
<input type="submit" id="submit" value="log In" onclick= "click()">

1 个答案:

答案 0 :(得分:1)

这不是一种安全的身份验证方法。此解决方案不应位于您要保证安全的任何系统上。身份验证应该在服务器上进行,而不是在客户端进行。

在您的问题中,如果用户在第一页上进行了身份验证,则永远不会检查第二页。为了检查这一点,您应该使用会话存储。

&#13;
&#13;
// LOGIN.js
function click() {
    inputname = $('#name').val();
    inputpassword =$('#pass').val();

    for (i in data.username )      //to match username with provided array
    { 
        name = data.username[i];

        for ( i in data.password){
            pass = data.password[i];

            if (inputname == name & inputpassword == pass ){
                //The user has successfully authenticated. We need to store this information
                //for the next page.
                sessionStorage.setItem("AuthenticationState", "Authenticated");
                
                //This authentication key will expire in 1 hour.
                sessionStorage.setItem("AuthenticationExpires", Date.now.addHours(1));
                
                //Push the user over to the next page.
                window.open('welcome1.html','_self');
            }               
        }
    }

    if (inputname != name & inputpassword != pass ){
        alert("Wrong Password");
    }
}

//addHours to a date.
//Credit to: Kennebec
//https://stackoverflow.com/questions/1050720/adding-hours-to-javascript-date-object
Date.prototype.addHours = function(h) {    
   this.setTime(this.getTime() + (h*60*60*1000)); 
   return this;   
}
&#13;
<!-- LOGIN.html --->

<input type="text" id="name" name="name" />
<input type="text" id="pass" name="pass" />
<input type="submit" id="sub" name="sub" onclick="click();" />
&#13;
&#13;
&#13;

然后在第二页上,检查用户是否经过身份验证。如果没有,请将它们推送到“拒绝访问”页面。

&#13;
&#13;
//Is the user authenticated?
if (sessionStorage.getItem('AuthenticationState') === null) {
   window.open("AccessDenied.html", "_self");
}
//Is their authentication token still valid?
else if (Date.now > new Date(sessionStorage.getItem('AuthenticationExpires'))) {
      window.open("AccessDenied.html", "_self");
}
else {
  //The user is authenticated and the authentication has not expired.
}
&#13;
&#13;
&#13;