我正在構建一個由tomcat服務的web應用程序(使用servlet api 2.4,並且此刻無法切換到servlet api 3.0)。 我試圖使用HttpServletRequest.isUserInRole動態保護某個url-pattern。Java HttpServletRequest isUserInRole無法正常工作(按請求安全性)servlet api 2.4
我有一個正在使用的web.xml文件確保多個servlet:
<servlet-mapping>
<servlet-name>MySecuredServlet</servlet-name>
<url-pattern>/my/secured/servlets/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>MyDispatcher</servlet-name>
<!-- This servlet won't be secured because only some of the servlets this dispatcher calls will be secured -->
<url-pattern>/my/dispatcher/*</url-pattern>
</servlet-mapping>
...
<security-constraint>
<web-resource-collection>
<url-pattern>/my/secured/servlets/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>admin</role-name>
</auth-constraint>
</security-constraint>
我也有我不能在web.xml文件中寫一些其他的servlet,因爲我不知道他們在建造時。
我正在向一些動態設置的servlet發送請求,其中一些需要授權。
class MyDispatcher extends HttpServlet {
...
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
// I am dispatching requests to dynamically set customServlets which I don't know at build time
MyCustomServlet customServlet = MyCustomServlets.get(req.getPathInfo());
if (customServlet != null) {
if (customServlet.requiresAuthorization()) {
// isUserInRole is not reliable. It returns false when it should return true. Why?
if (!req.isUserInRole(ADMIN_ROLE_NAME)) {
resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
}
customServlet.doGet(req, resp);
}
}
}
進一步澄清:
在url-pattern的/管理我服務,其固定在web.xml文件中的頁面。
在這個頁面我做的XMLHttpRequest的動態servlet和我預期的isUserInRole 方法返回真正因爲訪問/管理當最初的用戶認證。
但必須isUserInRole返回所有請求假直到我刷新/管理頁面在瀏覽器中。爲什麼會發生?我該如何解決它?