我需要知道如何覆盖 shiro 未经授权的页面。即,当用户对受保护的 url 没有某些权限时,shiro 返回页面 401。我们如何使其将用户转发到预定义的未经授权的页面?
谢谢...
我发现只有一种方法,如何将重定向更改为 login.jsp 以响应 401。
您应该创建自己的过滤器,它将扩展 org.apache.shiro.web.filter.authc.FormAuthenticationFilter,并覆盖 saveRequestAndRedirectToLogin() 方法。
public class SecurityAuthenticationFilter extends FormAuthenticationFilter {
@Override
protected void saveRequestAndRedirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
saveRequest(request);
sendChallenge(response);
}
protected void sendChallenge(ServletResponse response) {
HttpServletResponse httpResponse = WebUtils.toHttp(response);
httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
}
我使用 Guice + Shiro 集成。所以,这个过滤器的添加方式与 org.apache.shiro.guice.web.ShiroWebModule 中的相同。
public class SecurityModule extends ShiroWebModule {
public static final Key<SecurityAuthenticationFilter> AUTHC_REST = Key.get(SecurityAuthenticationFilter.class);
...
@Override
protected void configureShiroWeb() {
...
// Add as filter
addFilterChain("/rest/login", ANON);
addFilterChain("/rest/**", AUTHC_REST);
...
}
}
对于 shiro.ini 文件,应按以下方式添加:
[main]
authc = package.path.to.SecurityAuthenticationFilter
[urls]
/rest/login = anon
/rest/** = authc
这应该工作:)
:) 我需要相反的方式,我想获得一个401
而不是重定向(302
)。您当前的设置是什么?你可以从shiro.ini
文件中配置它吗?
不确定您使用的是哪种技术堆栈,但在 Java webapp 中,您可以在标签内的 web.xml 中进行配置。
<error-page>
<error-code>401</error-code>
<location>{path to custom page}</location>
</error-page>