shiro无权限访问时unauthorizedUrl不起作用

本文探讨了Shiro框架在权限验证失败时的默认行为,并提供了解决方案,通过自定义异常处理来优雅地处理未授权访问,避免直接报错。同时,介绍了如何在Spring MVC中配置异常解析器,实现特定异常跳转到指定页面。
/**
     * 读ShiroFilterFactoryBean源码可知,只有满足一下条件没有权限访问的时候才会跳转到配置的unauthorizedUrl页面
     * if (StringUtils.hasText(unauthorizedUrl) && (filter instanceof AuthorizationFilter)) {
     * 由于此处是认证过滤器,非授权过滤器,所以,访问没有权限时,页面会直接报错,很不友好,解决办法:加入spring异常处理
     * @return
     */
    @RequiresPermissions("/user/list.do")
    @RequestMapping("/list.do")
    public String userList() {
        return "user/list";
    }

异常处理配置:

package com.sniper.shiro.security.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

/**
 * 异常统一处理,捕获异常,跳转到对应视图
 * @author sniper
 *
 */
public class ShiroExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex) {
        if(ex instanceof UnauthorizedException) {
            return new ModelAndView("redirect:/refuse.jsp");  
        }
        return new ModelAndView("redirect:/exception.jsp");
    }

}

springmvc.xml

<bean id="exceptionResolver" class="com.sniper.shiro.security.web.interceptor.ShiroExceptionResolver"/>


转载于:https://my.oschina.net/sniperLi/blog/650627

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值