Конфликт WebFilter и RewriteConfiguration
Итак, у меня есть эта RewriteConfiguration:
@RewriteConfiguration
public class ApplicationConfigurationProvider extends HttpConfigurationProvider {
/**
* Set the forwarding rules
* @param context
* @return The forwarding rules
*/
@Override
public Configuration getConfiguration(ServletContext context) {
return ConfigurationBuilder.begin()
.addRule()
.when(Path.matches("/secure/{path}.xhtml?"))
.perform(Log.message(Level.INFO, "Server requested path: /secure/{path}"))
.addRule(Join.path("/login").to("/public/login.xhtml"))
.perform(Log.message(Level.INFO, "Forwarded: login"))
.addRule()
.when(Path.matches("/{path}").andNot(Path.matches("/login")))
.perform(Log.message(Level.INFO, "Forwarded': {path}"))
.addRule()
.when(Path.matches("/{path}"))
.perform(Forward.to("/secure/{path}.xhtml"))
;
}
/**
*
* @return
*/
@Override
public int priority() {
return 0;
}
}
И этот фильтр:
@WebFilter(filterName = "AuthorizationFilter", urlPatterns = {"/secure/*"})
public class AuthorizationFilter implements Filter {
/**
* Function that filters out unauthorized users and returns them to the login page
* when they try to visit secured pages
* @param request
* @param response
* @param chain
* @throws ServletException
* @throws IOException
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
HttpServletRequest req = (HttpServletRequest) request;
AuthorizationBean auth = (AuthorizationBean) req.getSession().getAttribute("authBean");
if (auth == null || !auth.isLoggedIn()) {
// User is not logged in, so redirect to login page.
HttpServletResponse res = (HttpServletResponse) response;
res.sendRedirect(req.getContextPath() + "/public/login.xhtml");
} else {
// User is logged in, so just continue request.
chain.doFilter(request, response);
}
}
/**
*
*/
@Override
public void destroy() {
}
/**
*
* @param fc
*/
@Override
public void init(FilterConfig fc) {
}
}
Проблема, с которой я сталкиваюсь, заключается в том, что когда я, например, обращаюсь к профилю страницы " http://localhost:8080/webapp/profile ", это защищенный файл, поэтому есть страница "/secure/profile.xhtml", но из-за rewriteConfiguration, просто "профиль" также работает. Но проблема в том, что WebFiler не захватывает "профиль", а только " http://localhost:8080/webapp/secure/profile.xhtml ".
Есть ли способ, что перезаписанные страницы из "защищенного" также попадают в фильтр? Так что, когда я открываю страницу "профиль", она обрабатывается так же, как "/secure/profile.xhtml".
1 ответ
Эта конструкция действительно потерпит неудачу, как описано, когда фильтр перезаписи запускается до фильтра аутентификации, а фильтр перезаписи выполняет внутренне RequestDispatcher#forward()
позвонить на целевой источник.
Фильтры по умолчанию слушают только прямые запросы. Вы должны явно добавить FORWARD
Диспетчер позволяет фильтру прослушивать переадресованные запросы.
@WebFilter(
filterName = "authorizationFilter",
urlPatterns = {"/secure/*"},
dispatcherTypes = {DispatcherType.REQUEST, DispatcherType.FORWARD}
)
Или в web.xml
вкус:
<filter-mapping>
<filter-name>authorizationFilter</filter-name>
<url-pattern>/secure/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>