基本身份验证:是否可以像getRemoteUser()一样setRemoteUser

时间:2012-06-27 11:52:14

标签: jsp servlets security

您好我使用基本身份验证方法来保护我的Webapp中的某些页面。其中有一个指定的url模式如下:

<url-pattern>/Important/*</url-pattern>
<auth-method>BASIC</auth-method>

现在的问题是,如果用户使用登录表单以正常方式登录。数据将发布到我的servlet,验证用户名和密码,然后继续进行。有没有办法在这个servlet中设置setRemoteUser,因为一旦用户尝试访问Important文件夹中的页面,就会再次出现身份验证输入。有没有办法可以通知身份验证机制用户已经登录?

2 个答案:

答案 0 :(得分:3)

这是不可能的。如果您实际上有用于登录的HTML <form>,那么您应该将身份验证方法从BASIC更改为FORM

<login-config>
    <auth-method>FORM</auth-method>
    <form-login-config>
        <form-login-page>/login.jsp</form-login-page>
        <form-error-page>/error.jsp</form-error-page>
    </form-login-config>
</login-config>

您还需要确保您的HTML <form>使用用户名和密码作为预先确定的参数j_security_checkj_username提交到预先确定的网址j_password

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

这样,容器将按照您需要的方式设置登录,getRemoteUser()将提供用户名。此外,任何直接访问受限URL的未经身份验证的用户都将自动转发到登录页面。成功登录后,它将自动转发回最初请求的页面。

此外,在Servlet 3.0兼容容器(Tomcat 7,Glassfish 3等)上使用FORM身份验证方法时,您将能够通过Servlet 3.0引入的HttpServletRequest#login()方法以编程方式登录用户在servlet中。这允许对过程和验证进行更细粒度的控制。 BASIC身份验证无法做到这一点。

BASIC身份验证是完全不同的事情。它显示了一个带有用户名/密码输入的简单JavaScript外观对话框。这不需要/使用HTML <form>或其他东西。它还将身份验证信息存储在客户端,并在每个后续请求中作为请求标头发送。它不会将身份验证信息存储在服务器端会话中,如FORM身份验证。

另见:

答案 1 :(得分:0)

如果用户尚未登录,方法HttpServletRequest.getRemoteUser()将返回null

所有类型的身份验证都适用。

以下是API文档所说的内容:

java.lang.String getRemoteUser()

Returns the login of the user making this request, if the user has been 
authenticated, or null if the user has not been authenticated. Whether the user 
name is sent with each subsequent request depends on the browser and type of      
authentication. Same as the value of the CGI variable REMOTE_USER.

Returns:
    a String specifying the login of the user making this request, 
   or null if the user login is not known