Restrict JSP/Servlet access to specific users only

时光总嘲笑我的痴心妄想 提交于 2019-12-18 06:53:45

问题


I'm developing a web app. I'd like to be able to let some friends see it, but not others that stumble upon the url. I was going to put a landing page and then a simple password box. Once the correct password is entered, I'd just record it in the session and expose the site as usual for the rest of the time they keep the browser open.

Is there a standard way to do this? I'd be adding extra code to my webapp to support this, I'm not sure if there's a built-in way to do it already (I'm using java servlets).

Thanks


回答1:


You can use container managed authentication using deployment descriptors. This requires no extra code in your side expect of a simple login form with an input and password field which submits to the URL j_security_check. Here's a basic example:

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

Assuming that you've private pages in a folder named /private and the above login page is located in /private/login.jsp, then add the following entries to the webapp's 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>

Then, in the servletcontainer which you're using you need to configure a so-called Realm for Private. Since it's unclear which servletcontainer you're using, here's a Tomcat 8.0 targeted document: Realm Configuration HOW-TO. You can configure it to verify the username/password combo against a XML file or a database or even a custom location.


A completely different alternative is to homegrow a login mechanism with help of a Filter which checks the presence of the logged-in user in the session scope. See this and this answer how to achieve this.




回答2:


You should think about using simple authentication using htaccess

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



来源:https://stackoverflow.com/questions/3134228/restrict-jsp-servlet-access-to-specific-users-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!