【问题标题】:Restrict JSP/Servlet access to specific users only将 JSP/Servlet 访问限制为仅特定用户
【发布时间】:2011-03-09 05:36:11
【问题描述】:

我正在开发一个网络应用程序。我希望能够让一些朋友看到它,而不是让其他偶然发现该网址的朋友看到​​它。我打算放一个登陆页面,然后放一个简单的密码框。输入正确的密码后,我只需将其记录在会话中,并在他们保持浏览器打开的剩余时间里照常公开网站。

有没有标准的方法来做到这一点?我会在我的 web 应用程序中添加额外的代码来支持这一点,我不确定是否已经有内置的方法可以做到这一点(我正在使用 java servlet)。

谢谢

【问题讨论】:

    标签: jsp servlets security-constraint


    【解决方案1】:

    您可以使用container managed authentication using deployment descriptors。这不需要额外的代码,只需一个简单的登录表单,其中包含提交到 URL j_security_check 的输入和密码字段。这是一个基本示例:

    <form action="j_security_check" method="post">
        <input type="text" name="j_username">
        <input type="password" name="j_password">
        <input type="submit">
    </form>
    

    假设您在名为/private 的文件夹中有私有页面,并且上述登录页面位于/private/login.jsp,则将以下条目添加到webapp 的web.xml

    <security-constraint>
        <web-resource-collection>
            <web-resource-name>Private</web-resource-name>
            <url-pattern>/private/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <role-name>friends</role-name>
        </auth-constraint>
    </security-constraint>
    
    <login-config>
        <auth-method>FORM</auth-method>
        <realm-name>Private</realm-name>
        <form-login-config>
            <form-login-page>/private/login.jsp</form-login-page>
            <form-error-page>/private/error.jsp</form-error-page>
        </form-login-config>
    </login-config>
    

    然后,在您使用的servletcontainer 中,您需要为Private 配置一个所谓的Realm。由于不清楚您使用的是哪个 servletcontainer,这里有一个针对 Tomcat 8.0 的文档:Realm Configuration HOW-TO。您可以将其配置为针对 XML 文件或数据库甚至自定义位置验证用户名/密码组合。


    一个完全不同的替代方法是在Filter 的帮助下自行开发一种登录机制,该机制检查登录用户在会话范围内的存在。请参阅thisthis 回答如何实现这一点。

    【讨论】:

      【解决方案2】:

      您应该考虑使用 htaccess 进行简单身份验证

      http://www.elated.com/articles/password-protecting-your-pages-with-htaccess/

      【讨论】:

      • 这是特定于 Apache HTTPD 的。这只有在他使用 Apache HTTPD 服务器作为 JSP/Servlet 容器前的代理时才有效。
      猜你喜欢
      • 1970-01-01
      • 2013-08-16
      • 2021-01-28
      • 2017-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多