简体   繁体   English

使用 javascript 从 html 页面限制客户端

[英]Restrict client from html page using javascript

I serve a HTML page, which presents within my users-authentication system.我提供一个 HTML 页面,该页面出现在我的用户身份验证系统中。

The HTML page should be unreachable when non-authenticated client tries to access it.当未经身份验证的客户端尝试访问 HTML 页面时,该页面应该无法访问。

So, I have the following JS code:所以,我有以下 JS 代码:

let isAuthenticated = false;
let username;

(async () => {
    // Retrieve username if logged-in
    try {
        const serverResponse = await fetch('api/auth/getUsername', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('auth_token') || ''}`,
            },
        });
        const serverResponseData = await serverResponse.json();

        if (serverResponseData.success) {
            isAuthenticated = true;
            username = serverResponseData.data.username;
        } else {
            return window.location.href = '/';
        }
    } catch { } finally {
        $(document).ready(() => {
            // Username and auth buttons elements
            const $authButtonsContainerELM = $('#authButtonsContainer');
            const $navUserContainerELM = $('#navUserContainer');
            const $usernameText = $('#usernameText');

            if (isAuthenticated) {
                $authButtonsContainerELM.css('display', 'none');
                $navUserContainerELM.css('display', 'flex');
                $usernameText.html(username);
            } else {
                $authButtonsContainerELM.css('display', 'flex');
                $navUserContainerELM.css('display', 'none');
            }
        });
    }
})();

And here is my HTML code:这是我的 HTML 代码:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>post blog</title>

    <link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
</head>

<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="js/libs/jquery.min.js">\x3C/script>');</script>

    <script src="./JS/index.js"></script>

    <div>blbalalal</div>
</body>

</html>

Note that the actual HTML code in my source is a bit more complex of-course.请注意,我源代码中的实际 HTML 代码当然要复杂一些。

So basically when I go as not authenticated in my browser, I try to access this page.所以基本上当我 go 在我的浏览器中未通过身份验证时,我尝试访问此页面。 What happens is, I can see the HTML page for 1 sec then I got redirect back to / path.发生的事情是,我可以看到 HTML 页面 1 秒,然后我被重定向回/路径。 But I do see the HTML. How can I execute my JS code before the HTML loads?但我确实看到了 HTML。如何在 HTML 加载之前执行我的 JS 代码?

I would suggest you to store the auth_token in a cookie... Instead of localStorage .我建议您将auth_token存储在 cookie 中......而不是localStorage So the cookie would be sent along the HTTP request... And the decision to serve the protected content would be made server-side.因此 cookie 将沿着 HTTP 请求发送...并且服务受保护内容的决定将由服务器端做出。

But if you insist... Just to practice ... You could hide the HTML by default via CSS for that split second:但是如果你坚持......只是为了练习......你可以在瞬间通过 CSS 默认隐藏 HTML:

Add the hiddenOnLoad class to the HTML markup:hiddenOnLoad class 添加到 HTML 标记中:

<body class="hiddenOnLoad">

Which would just hide everything:这只会隐藏一切:

body.hiddenOnLoad *{
  display: none !important;
}

And inside $(document).ready() ... It the authentication succeeded:$(document).ready()里面……认证成功了:

if(isAuthenticated){
  $("body").removeClass("hiddenOnLoad")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 限制用户访问页面而不使用javascript登录 - Restrict user from visiting a page without logging in using javascript 在使用 css、javascript 和 ZE1BFD762321E409CEEZ4AC0B66 时,我如何限制 HTML 表的打印页面中的特定行数 - how can i restrict no of specific rows in print page for a HTML table in using css , javascript and php 如何使用JQuery / Javascript / HTML限制浏览器一次显示完整的页面数据 - How to restrict browser to display complete page data at once using JQuery/Javascript/HTML 如何使用JavaScript或jQuery将html页面导出到客户端的pdf? - How to export a html page to pdf in client side using JavaScript or jQuery? 使用javascript从wordpress页面读取HTML - Using javascript to read HTML from a wordpress page 使用 javascript 从 html 页面获取数据 - get data from html page using javascript 我们如何限制/限制用户使用javascript重新加载页面或浏览器向后或向前 - How can we constraint/restrict the user from page reloading or browser back or forward using javascript 如何在客户端使用javascript从HTML标签创建图像? - How to create image from HTML tags using javascript at client end? 从html页面使用javascript删除html标签 - remove the html tag using javascript from html page 使用Javascript集中新页面中的现有HTML页面 - Focus existing HTML page from new page using Javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM