Shiro 配置不起作用, setUnauthorizedUrl(“/403”) 不生效

Shiro 很多细节性知识记录在这,上篇Shiro @RequiresPermissions 和 RequiresRoles 注解不生效的解决方法,今天再分享个容易忽视的点,Shiro 配置不生效,比如 setUnauthorizedUrl(“/403”) 不起作用,或者其它的配置都没生效。

	shiroFilterFactoryBean.setLoginUrl("/login");
        // 登录成功后要跳转的链接
        shiroFilterFactoryBean.setSuccessUrl("/index");
        //未授权界面;
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");

首先我们要搞清楚一个事,这里配置的都是路径、地址,或者叫做程序入口,也就是接口,这不是资源文件,不是 resources 下的页面。

比如配置 “/login”,程序会去寻找接口 “/login”,一般程序里会做转向,转到 “login.html” 之类。

   @RequestMapping("/login")
    public String login(String userName, String password){
        ....
        return "login.html";
    }

所以,如果这些配置没生效,比如像未授权要跳转 403 页面,但没起作用(有),先看看是否有接收并且重定向到 403 页面

这是一种情况,如果以上没问题,setUnauthorizedUrl(“/403”) 设置未授权还是没生效,看看你那边是不是使用注解@RequiresRoles@RequiresPermissions授权的。

 /**
     * 删除用户
     */
    @RequiresPermissions("user:delete")
    @RequestMapping("/deleteUser")
    public String deleteUser() {
        request.setAttribute("message","删除用户");
        return "user";
    }

如果是,查看控制台是否报异常

org.apache.shiro.authz.AuthorizationException: Not authorized to invoke method

出现这异常,那还需要处理这个异常,在ShiroConfig中添加如下代码:

@Bean
 public SimpleMappingExceptionResolver resolver() {
        SimpleMappingExceptionResolver r = new SimpleMappingExceptionResolver();
        Properties mappings = new Properties();
        mappings.setProperty("UnauthorizedException", "403");
        r.setExceptionMappings(mappings);
        r.setDefaultErrorView("error");
        r.setExceptionAttribute("ex");     
        return r;
    }

 

本文由老郭种树原创,转载请注明:https://guozh.net/setunauthorizedurl-403-does-not-work/

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注