关于注解方式 进行鉴权

本文介绍如何利用 Spring AOP 和自定义注解实现权限控制功能,包括配置切面、处理异常及登录状态检查等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@Aspect
@Component
public class AuthRightAspect {
    private static final Logger LOGGER = LoggerFactory.getLogger(AuthRightAspect.class);

    @Autowired
    private AuthRightService authRightService;

    @Pointcut("@annotation(com.suning.uras.common.aop.AuthRight)")
    public void controllerAspect() {
        // Controller层切点
    }

    /**
     * 
     * 功能描述: 用户鉴权注解拦截<br>
     * 〈功能详细描述〉
     * 
     * @param joinPoint
     * @throws AuthRightFailedException
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @Before("controllerAspect()")
    public void doBefore(JoinPoint joinPoint) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();

        // 请求参数信息等日志记录
        String targetName = joinPoint.getTarget().getClass().getSimpleName();
        String methodName = joinPoint.getSignature().getName();
        LOGGER.info("----excute AuthRight aop----class name:" + targetName + ",method:" + methodName + ",requestURI:"
                + request.getRequestURI());

        Object[] args = joinPoint.getArgs();
        LOGGER.info("----excute AuthRight aop----joinPoint.getArgs():");
        for (int i = 0; i < args.length; i++) {
            LOGGER.info("----" + args[i]);
        }

        // 获取注解的权限CODE
        MethodSignature ms = (MethodSignature) joinPoint.getSignature();
        Method method = ms.getMethod();
        String rightCodes = method.getAnnotation(AuthRight.class).rightCode();
        String viewType = method.getAnnotation(AuthRight.class).viewType();

        // 抓取cookies的用户ID
        String userId = "";
        String loginToken = "";
        Cookie[] cookies = request.getCookies();
        if (null != cookies && cookies.length > 0) {
            getCookieInfo(userId, loginToken, cookies);
        }

        LOGGER.info("----excute AuthRight aop---- userId={}, rightCode={}", userId, rightCodes);
        // 判断userAuthorityList是否包含需要鉴权的CODE
        boolean authAuccess = authRightService.authRight(userId, loginToken, rightCodes);
        if (!authAuccess) {
            LOGGER.warn("----excute AuthRight aop----auth right filed!");
            if (ViewTypeConstants.VIEW_TYPE_FTL.equals(viewType)) {
                throw new AuthRightFailedException("rightCode auth right filed!");
            } else {
                throw new AuthRightJsonFailedException("rightCode auth right filed!");
            }
        } else {
            LOGGER.info("----excute AuthRight aop----auth right success!");
        }
    }

    /**
     * 
     * 功能描述: 获取cookie中的用户和LoginToken<br>
     * 〈功能详细描述〉
     *
     * @param userId
     * @param loginToken
     * @param cookies
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private void getCookieInfo(String userId, String loginToken, Cookie[] cookies) {
        for (Cookie cookie : cookies) {
            if ("loginToken".equals(cookie.getName())) {
                String cookieValue = cookie.getValue();
                String[] cookieValues = cookieValue.split("\\|");
                if (cookieValues.length > 1) {
                    loginToken = cookieValues[0];
                    userId = cookieValues[1];
                    break;
                }
            }
        }
    }
}

自定义的注解

/**
 * 〈一句话功能简述〉<br>
 * 〈功能详细描述〉
 * 
 * @author 15061841
 * @see [相关类/方法](可选)
 * @since [产品/模块版本] (可选)
 */
@Target(value = { ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AuthRight {
    String rightCode() default "";

    String viewType() default ViewTypeConstants.VIEW_TYPE_JSON;
}

spring-servelet.xml 关于鉴权的配置

<!-- 使用CGLIB自动创建代理Bean -->
    <aop:aspectj-autoproxy proxy-target-class="true">
    </aop:aspectj-autoproxy>

    <context:annotation-config />
    <context:component-scan base-package="com.suning.uras.admin.web" />

    <!-- 登陆权限插件包注解 -->
    <context:component-scan base-package="com.suning.uras.common" />

    <mvc:annotation-driven />

    <!-- mvc 登陆鉴权拦截器 -->
    <mvc:interceptors>
        <mvc:interceptor>
            <!-- 需要拦截的URL -->
            <mvc:mapping path="/*/**" />

            <bean class="com.suning.uras.common.interceptor.AuthLoginInterceptor">
                <!-- 登陆页面 -->
                <property name="loginUrl" value="/login.htm" />
                <!-- 放行URL配置 -->
                <property name="excludeList">
                    <list>
                        <value>/login.htm</value>
                        <value>/logout.htm</value>
                    </list>
                </property>
            </bean>
        </mvc:interceptor>
    </mvc:interceptors>

    <!--无权限异常处理页面 -->
    <bean id="exceptionResolver"
        class="com.suning.uras.common.exception.AuthRightFailedExceptionResolver"> 
        <!-- 
        class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        -->
        <property name="exceptionMappings">
            <props>
                <!-- 支持自定义异常跳转FTL页面或者响应JSON数据,格式要求:FTL页面以.ftl结尾,其他配置全部以JSON数据格式处理 -->
                <!-- JSON格式,根据实际无权限结果码配置,如果不配置,默认返回{"errorCode":"no_right","errorMessage":"无权限访问"} -->
                <!-- JSON格式数据支持JSONP,但是回调函数名称必须是callback-->
                <!-- JSON配置参考:

                 -->
                <prop key="com.suning.uras.common.exception.AuthRightFailedException">no_right.ftl</prop>
                <prop key="com.suning.uras.common.exception.AuthRightJsonFailedException">{"code":"1001","message":"no right message"}</prop>
            </props>
        </property>
        <property name="warnLogCategory" value="WARN"></property>
    </bean>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值