关于注解方式 进行鉴权

来源:互联网 发布:如何查询域名的ip地址 编辑:程序博客网 时间:2024/05/16 13:48
@Aspect@Componentpublic 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)@Documentedpublic @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>
原创粉丝点击