[英]How to prevent a user from directly accessing a page without using PHP
我正在开发一个登录页面,我想阻止用户在没有首先验证 website.com > website.com/dashboard.html 的情况下访问用户仪表板。 查找此问题时,我发现如何防止用户通过编写 URL 直接访问我的 html 页面? . 答案使用 PHP,但我的身份验证系统使用 JavaScript 来检查密码是否有效。 但是JavaScript不能和PHP一起用在一个JS文件中。 我考虑过使用 PHP,但为了一起使用它们,我必须在网页中包含我的 JS 代码,这是我不想要的。 如何实现?
您可以使用 sessionStorage 来检查用户是否登录。
在登录页面中设置 sessionStorage 并在仪表板上检查它,如果 session 不可用则重定向到登录页面。
您可以在每次用户登录时为 session 设置一个新密钥,并使用 API 进行检查以避免出现相同的 session 值。
// Store
SessionStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = SessionStorage.getItem("lastname");
好的,所以我真的不明白这个问题。 但是,我创建了一个可能有用的解决方案。
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<form action="dashboard.html" method="GET">
<input type="text" id="username" name="username" value="username">
<br>
<input type="password" id="password" name="password" value="password">
<br>
<button id="login">Login</button>
<br>
</form>
<script>
</script>
</body>
</html>
仪表板.html
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<h1 id="username">Welcome user</h1>
<button id="logout">Logout</button>
<script>
//Wait until the website has recvied a post request
//from the login page
const usernames = ["user1", "user2", "user3"]; //Change this to a
database
const passwords = ["pass1", "pass2", "pass3"]; //Change this to a database
var results = ""; //The results of the thing
const username = new URLSearchParams(window.location.search).get("username"); //Get the username
const password = new URLSearchParams(window.location.search).get("password"); //Get the password
if (username && password) { //If the user has entered a username and password
for (let i = 0; i < usernames.length; i++) {
if (username == usernames[i] && password == passwords[i]) { //Check if the username and password are correct
results = "success";
document.getElementById("username").innerHTML = "Welcome " + username; //Change the welcome message
break;
} else {
results = "failure";
document.location.href = "index.html"; //Redirect to login page if login failed change this to what you need this is just my case.
}
}
} else {
document.location.href = "index.html"; //Redirect to login page if
login failed change this to what you need this is just my case.
}
</script>
</body>
</html>
希望这有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.