gpt4 book ai didi

javascript - 如果未登录,则限制对 js 文件的访问

转载 作者:搜寻专家 更新时间:2023-11-01 04:51:35 24 4
gpt4 key购买 nike

我有一个用 .net vb 和 SQLServer 开发的应用程序,我想限制文件 js 对登录用户可用,否则返回 403 错误或类似错误。例如,用户只有在登录后才能media/js/controller/myController.js

我知道如何控制文件 aspx、ashx 和 ascx 在未登录时的实际显示,但不知道如何在他们直接在浏览器中访问链接时阻止对 js 文件的访问,例如 http://www.myapp.com/media/js/controller/myController.js。它显示了我的代码 javascript。

我怎样才能做到这一点?

更新

这是我的web.config 中的身份验证模式

<!--<authentication mode="Windows"/>-->
<authentication mode="Forms">
<forms name="AuthCookie" path="/" loginUrl="login.aspx" protection="All" timeout="2000">
<credentials passwordFormat="Clear" />
</forms>
</authentication>
<authorization>
<!--<allow roles="***" />
<deny users="*" />-->
<deny users="?" />
<allow users="*" />
</authorization>

最佳答案

我不确定您为什么要限制 JavaScript 文件,而是使用它通过 Controller 提供文件。

public class ScriptsController : Controller
{
//option 1. Have one method for all the files.
[LoggedIn]
public ActionResult Get(string fileName)
{
return File(Server.MapPath("~/media/js/" + fileName + ".js"), "text/javascript");
}
//option 2: have a method for each file
[LoggedIn]
public ActionResult main()
{
return File(Server.MapPath("~/media/js/main.js"), "text/javascript");
}
}

在路由配置中

public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{

routes.MapRoute(
"JSFiles",
"{controller}/{fileName}",
new { controller = "Scripts", action = "Get" }
);
}
}

如果您将此方法放入“ScriptsController”中,则 url 将类似于 http://www.myapp.com/Scripts/Get/main其中 main 是 javascript Controller 的名称。

为了防止直接下载,您可以在网络配置中设置或将文件放在服务器上的非服务位置。无论哪种方式。从长远来看,Web 配置可能会更好。

网络配置方式

<location path="media">
<system.web>
<authorization>
<deny users="*"/>
</authorization>
</system.web>
</location>

您还应该添加验证以防止用户提供您想要提供的 js 文件以外的文件(例如 web 配置等)

关于javascript - 如果未登录,则限制对 js 文件的访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37534787/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com