Java Code Examples for org.springframework.web.method.HandlerMethod#getMethod()

The following examples show how to use org.springframework.web.method.HandlerMethod#getMethod() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MvcUriComponentsBuilder.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * An alternative to {@link #fromMappingName(String)} that accepts a
 * {@code UriComponentsBuilder} representing the base URL. This is useful
 * when using MvcUriComponentsBuilder outside the context of processing a
 * request or to apply a custom baseUrl not matching the current request.
 * <p><strong>Note:</strong> This method extracts values from "Forwarded"
 * and "X-Forwarded-*" headers if found. See class-level docs.
 * @param builder the builder for the base URL; the builder will be cloned
 * and therefore not modified and may be re-used for further calls.
 * @param name the mapping name
 * @return a builder to prepare the URI String
 * @throws IllegalArgumentException if the mapping name is not found or
 * if there is no unique match
 * @since 4.2
 */
public static MethodArgumentBuilder fromMappingName(@Nullable UriComponentsBuilder builder, String name) {
	WebApplicationContext wac = getWebApplicationContext();
	Assert.notNull(wac, "No WebApplicationContext. ");
	Map<String, RequestMappingInfoHandlerMapping> map = wac.getBeansOfType(RequestMappingInfoHandlerMapping.class);
	List<HandlerMethod> handlerMethods = null;
	for (RequestMappingInfoHandlerMapping mapping : map.values()) {
		handlerMethods = mapping.getHandlerMethodsForMappingName(name);
		if (handlerMethods != null) {
			break;
		}
	}
	if (handlerMethods == null) {
		throw new IllegalArgumentException("Mapping not found: " + name);
	}
	else if (handlerMethods.size() != 1) {
		throw new IllegalArgumentException("No unique match for mapping " + name + ": " + handlerMethods);
	}
	else {
		HandlerMethod handlerMethod = handlerMethods.get(0);
		Class<?> controllerType = handlerMethod.getBeanType();
		Method method = handlerMethod.getMethod();
		return new MethodArgumentBuilder(builder, controllerType, method);
	}
}
 
Example 2
Source File: MvcInterceptorManager.java    From onetwo with Apache License 2.0 6 votes vote down vote up
@Override
public void onHandlerMethodsInitialized(Map<RequestMappingInfo, HandlerMethod> handlerMethods) {
	for(HandlerMethod hm : handlerMethods.values()){
		List<? extends MvcInterceptor> interceptors = null;
		try {
			interceptors = findMvcInterceptors(hm);
		} catch (Exception e) {
			throw new BaseException("find MvcInterceptor error for HandlerMethod: " + hm.getMethod(), e);
		}
		if(!interceptors.isEmpty()){
			AnnotationAwareOrderComparator.sort(interceptors);
			HandlerMethodInterceptorMeta meta = new HandlerMethodInterceptorMeta(hm, interceptors);
			interceptorMetaCaces.put(hm.getMethod(), meta);
			if(log.isDebugEnabled()){
				log.debug("MvcInterceptor: {} -> {}", hm.getMethod(), interceptors);
			}
		}
	}
}
 
Example 3
Source File: AuthorizationInterceptor.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
private void checkAuthorized(HttpServletRequest request, Object handler) throws Exception {
	if (!HttpMethod.OPTIONS.matches(request.getMethod())) {
     if (handler instanceof HandlerMethod) {
         HandlerMethod m = (HandlerMethod) handler;
         Class<?> controllerType = m.getBeanType();
         Method method = m.getMethod();

         if (isAnonymous(controllerType) || isAnonymous(method)) {
             return;
         }

         if (isAlwaysAllowed(controllerType) || isAlwaysAllowed(method)) {
                checkAuthorized(request);
            } else {
                checkAuthorized(request, getNamespace(controllerType), getName(method));
            }
     } else {
         checkAuthorized(request);
     }
	}
}
 
Example 4
Source File: RepeatSubmitInterceptor.java    From RuoYi-Vue with MIT License 6 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
{
    if (handler instanceof HandlerMethod)
    {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);
        if (annotation != null)
        {
            if (this.isRepeatSubmit(request))
            {
                AjaxResult ajaxResult = AjaxResult.error("不允许重复提交,请稍后再试");
                ServletUtils.renderString(response, JSONObject.toJSONString(ajaxResult));
                return false;
            }
        }
        return true;
    }
    else
    {
        return super.preHandle(request, response, handler);
    }
}
 
Example 5
Source File: MvcUriComponentsBuilder.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * An alternative to {@link #fromMappingName(String)} that accepts a
 * {@code UriComponentsBuilder} representing the base URL. This is useful
 * when using MvcUriComponentsBuilder outside the context of processing a
 * request or to apply a custom baseUrl not matching the current request.
 * @param builder the builder for the base URL; the builder will be cloned
 * and therefore not modified and may be re-used for further calls.
 * @param name the mapping name
 * @return a builder to to prepare the URI String
 * @throws IllegalArgumentException if the mapping name is not found or
 * if there is no unique match
 * @since 4.2
 */
public static MethodArgumentBuilder fromMappingName(UriComponentsBuilder builder, String name) {
	RequestMappingInfoHandlerMapping handlerMapping = getRequestMappingInfoHandlerMapping();
	List<HandlerMethod> handlerMethods = handlerMapping.getHandlerMethodsForMappingName(name);
	if (handlerMethods == null) {
		throw new IllegalArgumentException("Mapping mappingName not found: " + name);
	}
	if (handlerMethods.size() != 1) {
		throw new IllegalArgumentException("No unique match for mapping mappingName " +
				name + ": " + handlerMethods);
	}
	HandlerMethod handlerMethod = handlerMethods.get(0);
	Class<?> controllerType = handlerMethod.getBeanType();
	Method method = handlerMethod.getMethod();
	return new MethodArgumentBuilder(builder, controllerType, method);
}
 
Example 6
Source File: RateCheckInterceptor.java    From redislimiter-spring-boot with Apache License 2.0 6 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    if (!(handler instanceof HandlerMethod)) {
        return true;
    }
    boolean isSuccess = true;
    HandlerMethod handlerMethod = (HandlerMethod) handler;
    Method method = handlerMethod.getMethod();
    if (method.isAnnotationPresent(RateLimiter.class)) {
        isSuccess = handleStatic(method, request, response);
    }
    else if(method.isAnnotationPresent(DynamicRateLimiter.class)) {
        isSuccess = handleDynamic(method, request, response);
    }
    return isSuccess;
}
 
Example 7
Source File: AnnotationAuthorizingMethodInterceptor.java    From tools with MIT License 6 votes vote down vote up
@Override
public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) throws Exception {
    if (handler instanceof HandlerMethod) {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        String token = request.getHeader(this.authorizationInfo.getHeader());
        AuthorizationMetaData authorizationMetaData = this.authorizationListener.supplyAccess(token);
        if (authorizationMetaData == null) {
            throw new NoAccountException("Account not found");
        }
        if (this.methodInterceptors != null) {
            for (AnnotationHandler annotationHandler : methodInterceptors) {
                Annotation annotation = method.getAnnotation(annotationHandler.getAnnotationClass());
                if (annotation != null) {
                    annotationHandler.assertAuthorization(annotation, authorizationMetaData);
                }
            }
        }
        this.authorizationListener.authentication(token);
    }
    return true;
}
 
Example 8
Source File: AuthInterceptor.java    From myth with Apache License 2.0 6 votes vote down vote up
@Override
public boolean preHandle(final HttpServletRequest request,
                         final HttpServletResponse response,
                         final Object handler) throws Exception {
    if (handler instanceof HandlerMethod) {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        final Permission annotation = method.getAnnotation(Permission.class);
        if (Objects.isNull(annotation)) {
            return Boolean.TRUE;
        }
        final boolean login = annotation.isLogin();
        if (login) {
            if (!LoginServiceImpl.LOGIN_SUCCESS) {
                request.setAttribute("code", "404");
                request.setAttribute("msg", "请登录!");
                request.getRequestDispatcher("/").forward(request, response);
                return Boolean.FALSE;
            }
        }
    }
    return super.preHandle(request, response, handler);
}
 
Example 9
Source File: MvcUriComponentsBuilder.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * An alternative to {@link #fromMappingName(String)} that accepts a
 * {@code UriComponentsBuilder} representing the base URL. This is useful
 * when using MvcUriComponentsBuilder outside the context of processing a
 * request or to apply a custom baseUrl not matching the current request.
 * <p><strong>Note:</strong> This method extracts values from "Forwarded"
 * and "X-Forwarded-*" headers if found. See class-level docs.
 * @param builder the builder for the base URL; the builder will be cloned
 * and therefore not modified and may be re-used for further calls.
 * @param name the mapping name
 * @return a builder to prepare the URI String
 * @throws IllegalArgumentException if the mapping name is not found or
 * if there is no unique match
 * @since 4.2
 */
public static MethodArgumentBuilder fromMappingName(@Nullable UriComponentsBuilder builder, String name) {
	WebApplicationContext wac = getWebApplicationContext();
	Assert.notNull(wac, "No WebApplicationContext. ");
	Map<String, RequestMappingInfoHandlerMapping> map = wac.getBeansOfType(RequestMappingInfoHandlerMapping.class);
	List<HandlerMethod> handlerMethods = null;
	for (RequestMappingInfoHandlerMapping mapping : map.values()) {
		handlerMethods = mapping.getHandlerMethodsForMappingName(name);
		if (handlerMethods != null) {
			break;
		}
	}
	if (handlerMethods == null) {
		throw new IllegalArgumentException("Mapping not found: " + name);
	}
	else if (handlerMethods.size() != 1) {
		throw new IllegalArgumentException("No unique match for mapping " + name + ": " + handlerMethods);
	}
	else {
		HandlerMethod handlerMethod = handlerMethods.get(0);
		Class<?> controllerType = handlerMethod.getBeanType();
		Method method = handlerMethod.getMethod();
		return new MethodArgumentBuilder(builder, controllerType, method);
	}
}
 
Example 10
Source File: MvcUriComponentsBuilder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * An alternative to {@link #fromMappingName(String)} that accepts a
 * {@code UriComponentsBuilder} representing the base URL. This is useful
 * when using MvcUriComponentsBuilder outside the context of processing a
 * request or to apply a custom baseUrl not matching the current request.
 * <p><strong>Note:</strong> This method extracts values from "Forwarded"
 * and "X-Forwarded-*" headers if found. See class-level docs.
 * @param builder the builder for the base URL; the builder will be cloned
 * and therefore not modified and may be re-used for further calls.
 * @param name the mapping name
 * @return a builder to prepare the URI String
 * @throws IllegalArgumentException if the mapping name is not found or
 * if there is no unique match
 * @since 4.2
 */
public static MethodArgumentBuilder fromMappingName(UriComponentsBuilder builder, String name) {
	RequestMappingInfoHandlerMapping handlerMapping = getRequestMappingInfoHandlerMapping();
	List<HandlerMethod> handlerMethods = handlerMapping.getHandlerMethodsForMappingName(name);
	if (handlerMethods == null) {
		throw new IllegalArgumentException("Mapping mappingName not found: " + name);
	}
	if (handlerMethods.size() != 1) {
		throw new IllegalArgumentException("No unique match for mapping mappingName " +
				name + ": " + handlerMethods);
	}
	HandlerMethod handlerMethod = handlerMethods.get(0);
	Class<?> controllerType = handlerMethod.getBeanType();
	Method method = handlerMethod.getMethod();
	return new MethodArgumentBuilder(builder, controllerType, method);
}
 
Example 11
Source File: FormTokenInterceptor.java    From Mykit with Apache License 2.0 6 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    if (handler instanceof HandlerMethod) {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        FormToken annotation = method.getAnnotation(FormToken.class);
        if (annotation != null) {
            boolean needSaveSession = annotation.save();
            if (needSaveSession) {
                request.getSession(false).setAttribute("formToken", UUID.randomUUID().toString());
            }
            boolean needRemoveSession = annotation.remove();
            if (needRemoveSession) {
                if (isRepeatSubmit(request)) {
                    return false;
                }
                request.getSession(false).removeAttribute("formToken");
            }
        }
        return true;
    } else {
        return super.preHandle(request, response, handler);
    }
}
 
Example 12
Source File: AutoIdempotentInterceptor.java    From neural with MIT License 6 votes vote down vote up
/**
 * 预处理
 *
 * @param request
 * @param response
 * @param handler
 * @return
 * @throws Exception
 */
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    if (!(handler instanceof HandlerMethod)) {
        return true;
    }

    HandlerMethod handlerMethod = (HandlerMethod) handler;
    Method method = handlerMethod.getMethod();
    NeuralIdempotent methodAnnotation = method.getAnnotation(NeuralIdempotent.class);
    if (methodAnnotation != null) {
        try {
            // 幂等性校验, 校验通过则放行, 校验失败则抛出异常, 并通过统一异常处理返回友好提示
            return tokenService.checkToken(request);
        }catch (Exception ex){
            throw ex;
        }
    }

    //必须返回true,否则会被拦截一切请求
    return true;
}
 
Example 13
Source File: LoginAuthInterceptor.java    From RuoYi with Apache License 2.0 5 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
    if (handler instanceof HandlerMethod) {
        final HandlerMethod handlerMethod = (HandlerMethod) handler;
        final Class<?> clazz = handlerMethod.getBeanType();
        final Method method = handlerMethod.getMethod();

        if (clazz.isAnnotationPresent(LoginAuth.class) || method.isAnnotationPresent(LoginAuth.class)) {
            SysUser loginUser = ShiroUtils.getSysUser();
            return ObjectUtil.isNotNull(loginUser);
        }
    }
    return true;
}
 
Example 14
Source File: SSOPermissionInterceptor.java    From kisso with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * 判断权限是否合法,支持 1、请求地址 2、注解编码
 * </p>
 *
 * @param request
 * @param handler
 * @param token
 * @return
 */
protected boolean isVerification(HttpServletRequest request, Object handler, SSOToken token) {
    /*
     * URL 权限认证
     */
    if (SSOConfig.getInstance().isPermissionUri()) {
        String uri = request.getRequestURI();
        if (uri == null || this.getAuthorization().isPermitted(token, uri)) {
            return true;
        }
    }
    /*
     * 注解权限认证
     */
    HandlerMethod handlerMethod = (HandlerMethod) handler;
    Method method = handlerMethod.getMethod();
    Permission pm = method.getAnnotation(Permission.class);
    if (pm != null) {
        if (pm.action() == Action.Skip) {
            /**
             * 忽略拦截
             */
            return true;
        } else if (!"".equals(pm.value()) && this.getAuthorization().isPermitted(token, pm.value())) {
            /**
             * 权限合法
             */
            return true;
        }
    } else if (this.isNothingAnnotationPass()) {
        /**
         * 无注解情况下,设置为true,不进行期限验证
         */
        return true;
    }
    /*
     * 非法访问
     */
    return false;
}
 
Example 15
Source File: AuthResourceFilter.java    From app-engine with Apache License 2.0 4 votes vote down vote up
@Override
protected ModelAndView handleInternal(HttpServletRequest request, HttpServletResponse response,
                                      HandlerMethod handlerMethod) throws Exception {
    if (StringUtils.equals(request.getRequestURI(), "/error")
            || StringUtils.startsWith(request.getRequestURI(), "/swagger-resources")
            || StringUtils.endsWithAny(request.getRequestURI(), GlobalConstants.staticResourceArray)
            || !StringUtils.equals(profile, "prod")) {
        return super.handleInternal(request, response, handlerMethod);
    }

    RequestContext context = ThreadLocalContext.getRequestContext();
    context.setOriginRequest(request);

    AuthRequest authRequest = new AuthRequest(request);

    Method method = handlerMethod.getMethod();
    BaseInfo baseInfo = null;
    if (method.isAnnotationPresent(BaseInfo.class)) {
        baseInfo = method.getAnnotation(BaseInfo.class);
    }
    RateLimit rateLimit = null;
    if (method.isAnnotationPresent(RateLimit.class)) {
        rateLimit = method.getAnnotation(RateLimit.class);
    }

    AuthResponse authResponse;
    try {
        authResponse = authService.auth(authRequest, Optional.ofNullable(baseInfo));
    } catch (AuthException e) {
        LOGGER.debug("auth failed! path: " + request.getRequestURI() + " appId: " + request.getHeader(AuthService.ENGINE_APPID_HEADER)
                + " version: " + ClientVersion.valueOf(request.getHeader(ClientVersion.VERSION_HEADER)));
        throw e;
    }
    counterService.increment(StringUtils.substring(StringUtils.replace(request.getRequestURI(), "/", "."), 1));
    context.setCurrentUid(authResponse.getUid());
    context.setAppId(authResponse.getAppId());
    context.setOfficialApp(authResponse.getAppId() == GlobalConstants.DEFAULT_APPID);
    context.setIp(authResponse.getIp());
    context.setPlatform(authResponse.getPlatform());
    context.setAttribute("auth_type", authResponse.getAuthedBy());
    context.setClientVersion(authResponse.getClientVersion());

    if (rateLimit != null && (authRequest.getFrom() != AuthRequest.RequestFrom.INNER || !rateLimit.internalIgnore())) {
        rateLimitAuthService.auth(context, rateLimit);
    }

    return super.handleInternal(request, response, handlerMethod);
}
 
Example 16
Source File: CompensableHandlerInterceptor.java    From ByteTCC with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
		throws Exception {
	String transactionStr = request.getHeader(HEADER_TRANCACTION_KEY);
	if (StringUtils.isBlank(transactionStr)) {
		return;
	}

	if (HandlerMethod.class.isInstance(handler) == false) {
		return;
	}

	HandlerMethod hm = (HandlerMethod) handler;
	Class<?> clazz = hm.getBeanType();
	Method method = hm.getMethod();
	if (CompensableCoordinatorController.class.equals(clazz)) {
		return;
	} else if (ErrorController.class.isInstance(hm.getBean())) {
		return;
	}

	Transactional globalTransactional = clazz.getAnnotation(Transactional.class);
	Transactional methodTransactional = method.getAnnotation(Transactional.class);
	boolean transactionalDefined = globalTransactional != null || methodTransactional != null;
	Compensable annotation = clazz.getAnnotation(Compensable.class);
	if (transactionalDefined && annotation == null) {
		return;
	}

	SpringCloudBeanRegistry beanRegistry = SpringCloudBeanRegistry.getInstance();
	CompensableBeanFactory beanFactory = beanRegistry.getBeanFactory();
	CompensableManager compensableManager = beanFactory.getCompensableManager();
	TransactionInterceptor transactionInterceptor = beanFactory.getTransactionInterceptor();

	CompensableTransaction compensable = compensableManager.getCompensableTransactionQuietly();
	TransactionContext transactionContext = compensable.getTransactionContext();

	// byte[] byteArray = SerializeUtils.serializeObject(transactionContext);
	// String compensableStr = ByteUtils.byteArrayToString(byteArray);
	// response.setHeader(HEADER_TRANCACTION_KEY, compensableStr);
	// response.setHeader(HEADER_PROPAGATION_KEY, this.identifier);

	TransactionResponseImpl resp = new TransactionResponseImpl();
	resp.setTransactionContext(transactionContext);
	resp.setSourceTransactionCoordinator(beanRegistry.getConsumeCoordinator(null));

	transactionInterceptor.beforeSendResponse(resp);

}
 
Example 17
Source File: SSOSpringInterceptor.java    From kisso with Apache License 2.0 4 votes vote down vote up
/**
 * 登录权限验证
 * <p>
 * 方法拦截 Controller 处理之前进行调用。
 * </p>
 */
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    /**
     * 处理 Controller 方法
     * <p>
     * 判断 handler 是否为 HandlerMethod 实例
     * </p>
     */
    if (handler instanceof HandlerMethod) {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        Login login = method.getAnnotation(Login.class);
        if (login != null) {
            if (login.action() == Action.Skip) {
                /**
                 * 忽略拦截
                 */
                return true;
            }
        }

        /**
         * 正常执行
         */
        SSOToken ssoToken = SSOHelper.getSSOToken(request);
        if (ssoToken == null) {
            if (HttpUtil.isAjax(request)) {
                /*
                 * Handler 处理 AJAX 请求
                 */
                this.getHandlerInterceptor().preTokenIsNullAjax(request, response);
                return false;
            } else {
                /*
                 * token 为空,调用 Handler 处理
                 * 返回 true 继续执行,清理登录状态并重定向至登录界面
                 */
                if (this.getHandlerInterceptor().preTokenIsNull(request, response)) {
                    log.debug("logout. request url:" + request.getRequestURL());
                    SSOHelper.clearRedirectLogin(request, response);
                }
                return false;
            }
        } else {
            /*
             * 正常请求,request 设置 token 减少二次解密
             */
            request.setAttribute(SSOConstants.SSO_TOKEN_ATTR, ssoToken);
        }
    }

    /**
     * 通过拦截
     */
    return true;
}
 
Example 18
Source File: AuthenticationInterceptor.java    From XUpdateService with Apache License 2.0 4 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    System.out.println("----------【用户认证拦截器】-----------");

    // 如果不是映射到方法直接通过
    if (!(handler instanceof HandlerMethod)) {
        return true;
    }

    HandlerMethod handlerMethod = (HandlerMethod) handler;
    Method method = handlerMethod.getMethod();
    // 判断接口是否需要登录
    LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);

    if (loginRequired == null) { //没有 @LoginRequired 注解,无需认证
        return true;
    }

    // 判断是否存在令牌信息,如果存在,则允许登录
    String accessToken = TokenUtils.parseToken(request);

    if (StringUtils.isEmpty(accessToken)) {
        throw new ApiException("未携带token,请先进行登录", TOKEN_MISSING);
    }

    // 从Redis 中查看 token 是否过期
    Claims claims;
    try {
        claims = TokenUtils.parseJWT(accessToken);
    } catch (ExpiredJwtException e) {
        throw new ApiException("token失效,请重新登录", TOKEN_INVALID);
    } catch (SignatureException se) {
        throw new ApiException("token令牌错误", AUTH_ERROR);
    }

    String loginName = claims.getId();
    Account account = accountService.checkAccount(loginName);

    if (account == null) {
        throw new ApiException("用户不存在,请重新登录", TOKEN_INVALID);
    }
    // 当前登录用户@CurrentAccount
    request.setAttribute(Constants.CURRENT_ACCOUNT, account);
    return true;
}
 
Example 19
Source File: PrivilegeInterceptor.java    From molicode with Apache License 2.0 4 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    //如果是资源请求,如ResourceHttpRequestHandler, 直接返回true
    if(!(handler instanceof HandlerMethod)){
        return true;
    }
    HandlerMethod handlerMethod = (HandlerMethod) handler;
    LoginContext loginContext = LoginHelper.getLoginContext();
    if (loginContext == null) {
        return true;
    }
    Method method = handlerMethod.getMethod();
    Class handlerClass = method.getDeclaringClass();
    if (method == null || handlerClass == null) {
        return true;
    }
    UserAuthPrivilege annotation = method.getAnnotation(UserAuthPrivilege.class);
    if (annotation == null) {
        annotation = (UserAuthPrivilege) handlerClass.getAnnotation(UserAuthPrivilege.class);
    }
    if (annotation == null) {
        return true;
    }

    AcUser acUser = loginContext.getExtValue(CommonConstant.LoginContext.AC_USER, AcUser.class);
    RoleCodeEnum roleCodeEnum = RoleCodeEnum.Parser.parseToNullSafe(RoleCodeEnum.class, acUser.getRoleCode());
    if (roleCodeEnum == null) {
        //返回无权限
        this.responseNoAuth(request, response, false, StringUtils.EMPTY);
        return false;
    }

    //可切换掉整个系统的权限等级
    Integer safeLevel = Profiles.getInstance().getServerSafeLevel();
    int level = annotation.level();

    Integer userLevel = roleCodeEnum.getPrivilegeLevel();
    if (safeLevel != null && userLevel != CommonConstant.ROLE_LEVEL.ADMIN) {
        userLevel = Math.max(userLevel, safeLevel);
    }
    if (userLevel > level) {
        this.responseNoAuth(request, response, false, annotation.code());
        return false;
    }
    return true;
}
 
Example 20
Source File: QuickRequestInterceptor.java    From XUpdateService with Apache License 2.0 4 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object handler) throws Exception {
    System.out.println("----------【快速请求拦截器】-----------");

    // 如果不是映射到方法直接通过
    if (!(handler instanceof HandlerMethod)) {
        return true;
    }
    HandlerMethod handlerMethod = (HandlerMethod) handler;
    Method method = handlerMethod.getMethod();
    // 判断接口是否需要登录
    QuickRequest quickRequest = method.getAnnotation(QuickRequest.class);

    if (quickRequest == null) { //没有 @QuickRequest 注解,无需要校验
        return true;
    }

    // 获取客户端请求携带的时间戳
    String timeStamp = request.getHeader("X-TimeStamp");

    if (StringUtils.isEmpty(timeStamp)) {
        timeStamp = request.getParameter("timeStamp");
        if (StringUtils.isEmpty(timeStamp)) { //如果没有携带时间戳,也无需校验
            return true;
        }
    }

    String identity = IpUtils.getRealIp(request); //身份默认使用请求的ip地址

    //如果注释有需要登录验证,就使用token作为身份
    LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);
    if (loginRequired != null) { //没有 @LoginRequired 注解,无需认证
        String accessToken = TokenUtils.parseToken(request);
        if (!StringUtils.isEmpty(accessToken)) {
            identity = accessToken;
        }
    }

    String url = request.getRequestURL().toString();
    String methodName = method.getName();
    String key = "QuickRequest_".concat(url).concat(methodName).concat(identity);

    if (QuickRequestUtils.isQuickRequest(key, quickRequest, timeStamp)) {
        throw new ApiException("请求过于频繁,请稍后再试!", REQUEST_BEYOND_LIMIT);
    }
    return true;
}