我正在使用Apache Shiro开发JSF应用程序。我使用Shiro验证用户并将她重定向到主页没有问题。在我尝试访问登录页面时进行身份验证后,它不会将主页重定向到我。即使已经有登录用户,我也可以再次登录。正如BalusC在他的博客文章中提到的那样Programmatic Login。
[main]
credentialsMatcher = org.apache.shiro.authc.credential.PasswordMatcher
myRealm = com.example.security.myRealm
myRealm.credentialsMatcher = $credentialsMatcher
securityManager.realms = $myRealm
user = com.example.web.filter.FacesAjaxAwareUserFilter
user.loginUrl = /login.xhtml
[urls]
/login.xhtml = user
此过滤器来自博客文章。
public class FacesAjaxAwareUserFilter extends UserFilter {
private static final String FACES_REDIRECT_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<partial-response><redirect url=\"%s\"></redirect></partial-response>";
@Override
protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
HttpServletRequest req = (HttpServletRequest) request;
if ("partial/ajax".equals(req.getHeader("Faces-Request"))) {
response.setContentType("text/xml");
response.setCharacterEncoding("UTF-8");
response.getWriter().printf(FACES_REDIRECT_XML, req.getContextPath() + getLoginUrl());
}
else {
super.redirectToLogin(request, response);
}
}
}
问题是什么?如果用户已经过身份验证,我该如何重定向?
编辑:目前,如果用户已经过身份验证,我正在使用PostConstruct注释进行重定向。我愿意接受任何好的解决方案。
答案 0 :(得分:7)
在我尝试访问登录页面时进行身份验证后,它不会将主页重定向到我。即使已有登录用户
,我也可以再次登录
Shiro和自定义Shiro用户过滤器都不打算阻止这种情况。 Shiro没有内置设施。自定义Shiro用户过滤器仅在找到未经身份验证的用户时运行,而不是在找到已经过身份验证的用户时运行。
防止经过身份验证的用户直接访问登录页面是您自己的责任。根据业务要求,您可以执行以下操作:
请允许它。也许用户只想切换登录。如有必要,您可以有条件地显示如下消息:
<ui:fragment rendered="#{not empty request.remoteUser}">
You are already logged-in as #{request.remoteUser}.
By logging in as another user, you will be logged out.
</ui:fragment>
<h:form id="login">
...
</h:form>
不要允许,但请保持同一页面。有条理地隐藏登录表单并显示如下消息:
<ui:fragment rendered="#{not empty request.remoteUser}">
Hey, how did you end up here?
You are already logged-in as #{request.remoteUser}!
</ui:fragment>
<h:form id="login" rendered="#{empty request.remoteUser}">
...
</h:form>
当然,当用户已经登录时,请确保您的Web应用程序没有任何登录链接。
不允许它并重定向到所需的目标页面。这可以通过几种方式完成。最干净的方法是使用servlet过滤器。
@WebFilter(urlPatterns = "/login.xhtml")
public class LoginPageFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
if (request.getRemoteUser() != null)) {
response.sendRedirect(request.getContextPath() + "/home.xhtml"); // Redirect to home page.
} else {
chain.doFilter(req, res); // User is not logged-in, so just continue request.
}
}
// Add/generate init() and destroy() with NOOP.
}
You can also do this in a preRenderView
event listener。 @PostConstruct
可能为时已晚,因为此时可能已经提交了响应。请注意,在没有任何形式的反馈的情况下重定向可能会使最终用户感到困惑。在过滤器中,考虑传递应触发条件消息的附加参数。或者在preRenderView
事件侦听器中,设置闪存范围的消息。