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

The following examples show how to use org.springframework.web.method.HandlerMethod#getMethodAnnotation() . 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: EntandoOauth2Interceptor.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    if (handler instanceof HandlerMethod) {
        HandlerMethod method = (HandlerMethod) handler;
        if (method.hasMethodAnnotation(RequestMapping.class)) {
            UserDetails user = this.extractOAuthParameters(request);
            RestAccessControl rqm = method.getMethodAnnotation(RestAccessControl.class);
            if (null == rqm) {
                return true;
            }

            this.checkAuthorization(user, rqm.permission(), request);
        }
    }
    return true;
}
 
Example 2
Source File: PermissionInterceptor.java    From zuihou-admin-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 super.preHandle(request, response, handler);
    }

    if (!ifLogin(request)) {
        HandlerMethod method = (HandlerMethod) handler;
        PermessionLimit permission = method.getMethodAnnotation(PermessionLimit.class);
        if (permission == null || permission.limit()) {
            response.sendRedirect(request.getContextPath() + "/toLogin");
            //request.getRequestDispatcher("/toLogin").forward(request, response);
            return false;
        }
    }

    return super.preHandle(request, response, handler);
}
 
Example 3
Source File: UserAuthRestInterceptor.java    From sanshanblog with Apache License 2.0 6 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    HandlerMethod handlerMethod = (HandlerMethod) handler;
    // 配置该注解,说明进行用户拦截
    WantUserToken annotation = handlerMethod.getBeanType().getAnnotation(WantUserToken.class);
    if (annotation==null){
        annotation = handlerMethod.getMethodAnnotation(WantUserToken.class);
    }
    //判断在网关处鉴权
    String token = request.getHeader(userAuthConfig.getTokenHeader());
    if (StringUtils.isEmpty(token)) {
        if (annotation == null) {
            return super.preHandle(request, response, handler);
        }
    }
    //进行拦截
    IJWTInfo infoFromToken = userAuthUtil.getInfoFromToken(token);
    UserContextHandler.setUsername(infoFromToken.getUsername());
    UserContextHandler.setUserID(infoFromToken.getId());
    return super.preHandle(request, response, handler);
}
 
Example 4
Source File: PermissionInterceptor.java    From open-capacity-platform 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 super.preHandle(request, response, handler);
	}
	
	if (!ifLogin(request)) {
		HandlerMethod method = (HandlerMethod)handler;
		PermessionLimit permission = method.getMethodAnnotation(PermessionLimit.class);
		if (permission == null || permission.limit()) {
			response.sendRedirect(request.getContextPath() + "/toLogin");
			//request.getRequestDispatcher("/toLogin").forward(request, response);
			return false;
		}
	}
	
	return super.preHandle(request, response, handler);
}
 
Example 5
Source File: PermissionInterceptor.java    From xxl-mq with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

	if (!(handler instanceof HandlerMethod)) {
		return super.preHandle(request, response, handler);
	}

	if (!ifLogin(request)) {
		HandlerMethod method = (HandlerMethod)handler;
		PermessionLimit permission = method.getMethodAnnotation(PermessionLimit.class);
		if (permission == null || permission.limit()) {
			response.sendRedirect(request.getContextPath() + "/toLogin");
			//request.getRequestDispatcher("/toLogin").forward(request, response);
			return false;
		}
	}

	return super.preHandle(request, response, handler);
}
 
Example 6
Source File: LogInterceptor.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
    int index = request.getContextPath().length();
    String uri = request.getRequestURI().substring(index);
    String method = request.getMethod();
    String ip = remoteIp(request);
    HandlerMethod handlerMethod = (HandlerMethod) handler;
    AccessLog al = handlerMethod.getMethodAnnotation(AccessLog.class);
    if (al != null) {
        AdminModule module = al.module();
        String operation = al.operation();
        log.info("module={},operation={}", module, operation);
        int dotIndex = uri.lastIndexOf(".");
        String accessRuleUri = dotIndex > 0 ? uri.substring(0, dotIndex) : uri;
        Admin admin = (Admin) request.getSession().getAttribute(SysConstant.SESSION_ADMIN);
        long adminUid = admin == null ? -1 : admin.getId();
        AdminAccessLog adminAccessLog = new AdminAccessLog();
        adminAccessLog.setAdminId(adminUid);
        adminAccessLog.setAccessIp(ip);
        adminAccessLog.setAccessMethod(method);
        adminAccessLog.setOperation(operation);
        adminAccessLog.setModule(module);
        adminAccessLog.setUri(accessRuleUri);
        //解决service为null无法注入问题
        BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
        AdminAccessLogService logService = (AdminAccessLogService) factory.getBean("adminAccessLogService");
        logService.saveLog(adminAccessLog);
    }

    return true;
}
 
Example 7
Source File: WebAuth.java    From flow-platform-x with Apache License 2.0 5 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
    if (!authService.isEnabled()) {

        // do not update existing user
        if (sessionManager.exist()) {
            return true;
        }

        return authService.setAsDefaultAdmin();
    }

    String token = getToken(request);

    if (Objects.equals(token, MagicToken)) {
        return authService.setAsDefaultAdmin();
    }

    if (!authService.set(token)) {
        throw new AuthenticationException("Invalid token");
    }

    HandlerMethod handlerMethod = (HandlerMethod) handler;
    Action action = handlerMethod.getMethodAnnotation(Action.class);

    if (!authService.hasPermission(action)) {
        throw new AccessException("No permission");
    }

    return true;
}
 
Example 8
Source File: OpenApiInterceptor.java    From Jpom with MIT License 5 votes vote down vote up
@Override
protected boolean preHandle(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod) throws Exception {
    // 记录请求类型
    request.setAttribute("Page_Req", false);
    NotLogin methodAnnotation = handlerMethod.getMethodAnnotation(NotLogin.class);
    if (methodAnnotation == null) {
        if (handlerMethod.getBeanType().isAnnotationPresent(NotLogin.class)) {
            return true;
        }
    } else {
        return true;
    }
    return checkOpenApi(request, response);
}
 
Example 9
Source File: ClassUtil.java    From magic-starter with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 获取Annotation
 *
 * @param handlerMethod  HandlerMethod
 * @param annotationType 注解类
 * @param <A>            泛型标记
 * @return {Annotation}
 */
public static <A extends Annotation> A getAnnotation(HandlerMethod handlerMethod, Class<A> annotationType) {
	// 先找方法,再找方法上的类
	A annotation = handlerMethod.getMethodAnnotation(annotationType);
	if (null != annotation) {
		return annotation;
	}
	// 获取类上面的Annotation,可能包含组合注解,故采用spring的工具类
	Class<?> beanType = handlerMethod.getBeanType();
	return AnnotatedElementUtils.findMergedAnnotation(beanType, annotationType);
}
 
Example 10
Source File: OperationCustomizer.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
@Override
public Operation customize(Operation operation, HandlerMethod handlerMethod) {
	CustomizedOperation annotation = handlerMethod.getMethodAnnotation(CustomizedOperation.class);
	if (annotation != null) {
		operation.description(operation.getDescription() + ", " + annotation.addition());
	}
	return operation;
}
 
Example 11
Source File: SpringDocTestApp.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
OperationCustomizer operationCustomizer() {
	return (Operation operation, HandlerMethod handlerMethod) -> {
		CustomizedOperation annotation = handlerMethod.getMethodAnnotation(CustomizedOperation.class);
		if (annotation != null) {
			operation.description(StringUtils.defaultIfBlank(operation.getDescription(), Constants.DEFAULT_DESCRIPTION) + ", " + annotation.addition());
		}
		return operation;
	};
}
 
Example 12
Source File: ClassUtil.java    From blade-tool with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 获取Annotation
 *
 * @param handlerMethod  HandlerMethod
 * @param annotationType 注解类
 * @param <A>            泛型标记
 * @return {Annotation}
 */
public static <A extends Annotation> A getAnnotation(HandlerMethod handlerMethod, Class<A> annotationType) {
	// 先找方法,再找方法上的类
	A annotation = handlerMethod.getMethodAnnotation(annotationType);
	if (null != annotation) {
		return annotation;
	}
	// 获取类上面的Annotation,可能包含组合注解,故采用spring的工具类
	Class<?> beanType = handlerMethod.getBeanType();
	return AnnotatedElementUtils.findMergedAnnotation(beanType, annotationType);
}
 
Example 13
Source File: WebExceptionResolver.java    From microservices-platform with Apache License 2.0 5 votes vote down vote up
@Override
public ModelAndView resolveException(HttpServletRequest request,
		HttpServletResponse response, Object handler, Exception ex) {
	logger.error("WebExceptionResolver:{}", ex);

	// if json
	boolean isJson = false;
	HandlerMethod method = (HandlerMethod)handler;
	ResponseBody responseBody = method.getMethodAnnotation(ResponseBody.class);
	if (responseBody != null) {
		isJson = true;
	}

	// error result
	ReturnT<String> errorResult = new ReturnT<String>(ReturnT.FAIL_CODE, ex.toString().replaceAll("\n", "<br/>"));

	// response
	ModelAndView mv = new ModelAndView();
	if (isJson) {
		try {
			response.setContentType("application/json;charset=utf-8");
			response.getWriter().print(JacksonUtil.writeValueAsString(errorResult));
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
		return mv;
	} else {

		mv.addObject("exceptionMsg", errorResult.getMsg());
		mv.setViewName("/common/common.exception");
		return mv;
	}
}
 
Example 14
Source File: BaseJpomInterceptor.java    From Jpom with MIT License 5 votes vote down vote up
static boolean isPage(HandlerMethod handlerMethod) {
    ResponseBody responseBody = handlerMethod.getMethodAnnotation(ResponseBody.class);
    if (responseBody == null) {
        RestController restController = handlerMethod.getBeanType().getAnnotation(RestController.class);
        return restController == null;
    }
    return false;
}
 
Example 15
Source File: PermissionInterceptor.java    From xxl-job with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
	
	if (!(handler instanceof HandlerMethod)) {
		return super.preHandle(request, response, handler);
	}

	// if need login
	boolean needLogin = true;
	boolean needAdminuser = false;
	HandlerMethod method = (HandlerMethod)handler;
	PermissionLimit permission = method.getMethodAnnotation(PermissionLimit.class);
	if (permission!=null) {
		needLogin = permission.limit();
		needAdminuser = permission.adminuser();
	}

	if (needLogin) {
		XxlJobUser loginUser = loginService.ifLogin(request, response);
		if (loginUser == null) {
			response.sendRedirect(request.getContextPath() + "/toLogin");
			//request.getRequestDispatcher("/toLogin").forward(request, response);
			return false;
		}
		if (needAdminuser && loginUser.getRole()!=1) {
			throw new RuntimeException(I18nUtil.getString("system_permission_limit"));
		}
		request.setAttribute(LoginService.LOGIN_IDENTITY_KEY, loginUser);
	}

	return super.preHandle(request, response, handler);
}
 
Example 16
Source File: TokenHandlerInterceptor.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
private void internalPreProcess(HandlerMethod handlerMethod, HttpServletRequest request) {
    Token token = handlerMethod.getMethodAnnotation(Token.class);
    if (token != null) {
        if (token.check()) {
            if (!manager.isTokenValid(request, token.scope(), token.reset())) { throw new InvalidTokenException(); }
        }
        if (token.save()) {
            manager.saveToken(request, token.scope());
        }
    }
}
 
Example 17
Source File: WebExceptionResolver.java    From xxl-conf with GNU General Public License v3.0 5 votes vote down vote up
@Override
public ModelAndView resolveException(HttpServletRequest request,
		HttpServletResponse response, Object handler, Exception ex) {

	logger.error("WebExceptionResolver:{}", ex);

	// if json
	boolean isJson = false;
	HandlerMethod method = (HandlerMethod)handler;
	ResponseBody responseBody = method.getMethodAnnotation(ResponseBody.class);
	if (responseBody != null) {
		isJson = true;
	}

	// error result
	ReturnT<String> errorResult = new ReturnT<String>(ReturnT.FAIL.getCode(), ex.toString().replaceAll("\n", "<br/>"));

	// response
	ModelAndView mv = new ModelAndView();
	if (isJson) {
		try {
			response.setContentType("application/json;charset=utf-8");
			response.getWriter().print(JacksonUtil.writeValueAsString(errorResult));
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
		return mv;
	} else {

		mv.addObject("exceptionMsg", errorResult.getMsg());
		mv.setViewName("common/common.exception");
		return mv;
	}

}
 
Example 18
Source File: WebExceptionResolver.java    From lightconf with GNU General Public License v3.0 5 votes vote down vote up
@Override
public ModelAndView resolveException(HttpServletRequest request,
                                     HttpServletResponse response, Object handler, Exception ex) {

    log.error("WebExceptionResolver:{}", ex);

    // if json
    boolean isJson = false;
    HandlerMethod method = (HandlerMethod) handler;
    ResponseBody responseBody = method.getMethodAnnotation(ResponseBody.class);
    if (responseBody != null) {
        isJson = true;
    }

    // error result
    ReturnT<String> errorResult = new ReturnT<String>(ReturnT.FAIL.getCode(), ex.toString().replaceAll("\n", "<br/>"));

    // response
    ModelAndView mv = new ModelAndView();
    if (isJson) {
        try {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JacksonUtil.writeValueAsString(errorResult));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return mv;
    } else {

        mv.addObject("exceptionMsg", errorResult.getMsg());
        mv.setViewName("/common/common.exception");
        return mv;
    }

}
 
Example 19
Source File: InjectionAttackInterceptor.java    From spring-boot-start-current with Apache License 2.0 5 votes vote down vote up
private < T extends Annotation > T getHandlerAnnotation ( HandlerMethod handlerMethod ,
														  Class< T > clazz ) {
	T annotation = handlerMethod.getMethodAnnotation( clazz );
	if ( Objects.nonNull( annotation ) ) {
		return annotation;
	}
	return handlerMethod.getBeanType().getAnnotation( clazz );
}
 
Example 20
Source File: SecurityConfig.java    From eladmin with Apache License 2.0 4 votes vote down vote up
private Map<String, Set<String>> getAnonymousUrl(Map<RequestMappingInfo, HandlerMethod> handlerMethodMap) {
    Map<String, Set<String>> anonymousUrls = new HashMap<>(6);
    Set<String> get = new HashSet<>();
    Set<String> post = new HashSet<>();
    Set<String> put = new HashSet<>();
    Set<String> patch = new HashSet<>();
    Set<String> delete = new HashSet<>();
    Set<String> all = new HashSet<>();
    for (Map.Entry<RequestMappingInfo, HandlerMethod> infoEntry : handlerMethodMap.entrySet()) {
        HandlerMethod handlerMethod = infoEntry.getValue();
        AnonymousAccess anonymousAccess = handlerMethod.getMethodAnnotation(AnonymousAccess.class);
        if (null != anonymousAccess) {
            List<RequestMethod> requestMethods = new ArrayList<>(infoEntry.getKey().getMethodsCondition().getMethods());
            RequestMethodEnum request = RequestMethodEnum.find(requestMethods.size() == 0 ? RequestMethodEnum.ALL.getType() : requestMethods.get(0).name());
            switch (Objects.requireNonNull(request)) {
                case GET:
                    get.addAll(infoEntry.getKey().getPatternsCondition().getPatterns());
                    break;
                case POST:
                    post.addAll(infoEntry.getKey().getPatternsCondition().getPatterns());
                    break;
                case PUT:
                    put.addAll(infoEntry.getKey().getPatternsCondition().getPatterns());
                    break;
                case PATCH:
                    patch.addAll(infoEntry.getKey().getPatternsCondition().getPatterns());
                    break;
                case DELETE:
                    delete.addAll(infoEntry.getKey().getPatternsCondition().getPatterns());
                    break;
                default:
                    all.addAll(infoEntry.getKey().getPatternsCondition().getPatterns());
                    break;
            }
        }
    }
    anonymousUrls.put(RequestMethodEnum.GET.getType(), get);
    anonymousUrls.put(RequestMethodEnum.POST.getType(), post);
    anonymousUrls.put(RequestMethodEnum.PUT.getType(), put);
    anonymousUrls.put(RequestMethodEnum.PATCH.getType(), patch);
    anonymousUrls.put(RequestMethodEnum.DELETE.getType(), delete);
    anonymousUrls.put(RequestMethodEnum.ALL.getType(), all);
    return anonymousUrls;
}