SpringBoot中集成Shiro的時(shí)候祭椰, 配置setUnauthorizedUrl("/403")了泞歉,但是不起作用摩钙,只會(huì)在控制臺(tái)打印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疮跑,所以u(píng)nauthorizedUrl設(shè)置后不起作用,只會(huì)在控制臺(tái)打印異常信息凸舵。
接下來(lái)祖娘,我們需要做一些配置,自己來(lái)處理UnauthorizedException異常:
1.第一種方式
@Configuration
public class ExceptionConf {
@Bean
public SimpleMappingExceptionResolver resolver() {
SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
Properties properties = new Properties();
properties.setProperty("org.apache.shiro.authz.UnauthorizedException", "/403");
resolver.setExceptionMappings(properties);
return resolver;
}
}
當(dāng)然啊奄,還有其他的方法可以自己處理渐苏。
比如:
2.用spring mvc的統(tǒng)一異常處理類(lèi)HandlerExceptionResolver
定義一個(gè)類(lèi)繼承HandlerExceptionResolver
,然后判斷UnauthorizedException
異常即可菇夸。
public class MyExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
if (e instanceof UnauthorizedException) {
ModelAndView mv = new ModelAndView("/403");
return mv;
}
return null;
}
}
然后琼富,在啟動(dòng)類(lèi)中注冊(cè)該bean
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
// 注冊(cè)統(tǒng)一異常處理bean
@Bean
public MyExceptionResolver myExceptionResolver() {
return new MyExceptionResolver();
}
}
最后幫朋友打個(gè)小廣告