1. 首页
  2. >
  3. 编程技术
  4. >
  5. Java

shiro中setUnauthorizedUrl不起作用或setUnauthorizedUrl无效

SpringBoot中集成Shiro的时候, 配置setUnauthorizedUrl("/notPermit")了,但是不起作用,只会在控制台打印UnauthorizedException异常信息:
原因:

Shiro源码中是这样做的:


private void applyUnauthorizedUrlIfNecessary(Filter filter) {
        String unauthorizedUrl = this.getUnauthorizedUrl();
        if(StringUtils.hasText(unauthorizedUrl) && filter instanceof AuthorizationFilter) {
            AuthorizationFilter authzFilter = (AuthorizationFilter)filter;
            String existingUnauthorizedUrl = authzFilter.getUnauthorizedUrl();
            if(existingUnauthorizedUrl == null) {
                authzFilter.setUnauthorizedUrl(unauthorizedUrl);
            }
        }
    }
只有perms,roles,ssl,rest,port才是属于AuthorizationFilter,而anon,authcBasic,authc,user是AuthenticationFilter,所以unauthorizedUrl设置后不起作用,只会在控制台打印异常信息。

接下来,我们需要做一些配置,自己来处理UnauthorizedException异常:
@Configuration
public class ExceptionConf {
    @Bean
    public SimpleMappingExceptionResolver resolver() {
        SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
        Properties properties = new Properties();
        properties.setProperty("org.apache.shiro.authz.UnauthorizedException", "/notPermit");
        resolver.setExceptionMappings(properties);
        return resolver;
    }
}


再次测试就正常跳转到notPermit了。