Object target = context.routeTarget(); if (null == target) { Class<?> clazz = context.routeAction().getDeclaringClass(); target = WebContext.blade().getBean(clazz); if (context.targetType() == RouteHandler.class) { RouteHandler routeHandler = (RouteHandler) target; routeHandler.handle(context); } else if (context.targetType() == RouteHandler0.class) { RouteHandler0 routeHandler = (RouteHandler0) target; routeHandler.handle(context.request(), context.response()); } else { Method actionMethod = context.routeAction(); Class<?> returnType = actionMethod.getReturnType(); if (!context.isIE()) { context.contentType(Const.CONTENT_TYPE_JSON); } else { context.contentType(Const.CONTENT_TYPE_HTML); context.routeParameters() : null); context.json(returnParam); return; context.body( ViewBody.of(new ModelAndView(returnParam.toString())) );
@Override public boolean before(RouteContext context) { if (xssOption.isExclusion(context.uri())) { return true; } this.filterHeaders(context.headers()); this.filterParameters(context.parameters()); if (context.contentType().toLowerCase().contains("json")) { String body = context.bodyToString(); if (StringKit.isNotEmpty(body)) { String filterBody = stripXSS(body); context.body(new StringBody(filterBody)); } } return true; }
@Override public void handle(WebContext webContext) throws Exception { RouteContext context = new RouteContext(webContext.getRequest(), webContext.getResponse()); // if execution returns false then execution is interrupted String uri = context.uri(); Route route = webContext.getRoute(); if (null == route) { throw new NotFoundException(context.uri()); } // init route, request parameters, route action method and parameter. context.initRoute(route); // execution middleware if (hasMiddleware && !invokeMiddleware(routeMatcher.getMiddleware(), context)) { return; } context.injectParameters(); // web hook before if (hasBeforeHook && !invokeHook(routeMatcher.getBefore(uri), context)) { return; } // execute this.routeHandle(context); // webHook if (hasAfterHook) { this.invokeHook(routeMatcher.getAfter(uri), context); } }
@Override public boolean before(RouteContext context) { boolean isAuth = false; for (String startExclusion : urlStartExclusions) { if ("/".equals(startExclusion) || context.uri().startsWith(startExclusion)) { isAuth = true; break; } } if (!isAuth) { return true; } String authorization = context.header("Authorization"); String user = this.searchCredential(authorization); if (null == user) { context.header("WWW-Authenticate", this.realm).status(401); return false; } return true; }
public String genToken(RouteContext context) { String tokenUUID = context.session().attribute(sessionToken); if (StringKit.isEmpty(tokenUUID)) { tokenUUID = UUID.UU64(); context.session().attribute(sessionToken, tokenUUID); } String token = Base64.getEncoder().encodeToString(PasswordKit.hashPassword(tokenUUID).getBytes()); context.attribute("_csrf_token", token); context.attribute("_csrf_token_input", "<input type='hidden' name='_token' value='" + token + "'/>"); return token; }
.get("/", ctx -> { String[] chars = new String[]{"Here a special char \" that not escaped", "And Another \\ char"}; ctx.json(chars); }) .get("/user/aa", ctx -> ctx.render("upload.html")) .get("/up", ctx -> ctx.render("upload.html")) .get("/d1", ctx -> { File file = new File("/Users/biezhi/Pictures/rand/003.jpg"); ctx.response().contentType("image/jpeg"); ctx.response().header("Content-Disposition", "attachment; filename=003.jpg"); ctx.response().body(ByteBody.of(file)); }) .get("/d2", ctx -> { File file = new File("/Users/biezhi/Pictures/rand/003.jpg"); try (FileInputStream inputStream = new FileInputStream(file)) { ctx.response().contentType("image/jpef"); ctx.response().header("Content-Disposition", "attachment; filename=m1.png"); ctx.response().body(StreamBody.of(inputStream)); } catch (IOException e) { e.printStackTrace(); .get("/d3", ctx -> { String str = "hello world"; ctx.response().contentType("text/html"); ctx.response().body(ByteBody.of(str.getBytes())); }) .get("/error", ctx -> { int a = 1 / 0; ctx.text("ok");
@Override public boolean before(RouteContext context) { if (csrfOption.isIgnoreMethod(context.method())) { if (csrfOption.isStartExclusion(context.uri())) { return true; } this.genToken(context); return true; } if (csrfOption.isExclusion(context.uri())) { return true; } String tokenUUID = context.session().attribute(sessionToken); if (StringKit.isEmpty(tokenUUID)) { csrfOption.getErrorHandler().accept(context); return false; } String token = csrfOption.getTokenGetter().apply(context.request()); if (StringKit.isEmpty(token)) { csrfOption.getErrorHandler().accept(context); return false; } String hash = new String(Base64.getDecoder().decode(token)); if (!PasswordKit.checkPassword(tokenUUID, hash)) { csrfOption.getErrorHandler().accept(context); return false; } return true; }
return context; } else if (argType == Request.class) { return context.request(); } else if (argType == Response.class) { return context.response(); } else if (argType == Session.class || argType == HttpSession.class) { return context.request().session(); } else if (argType == FileItem.class) { return new ArrayList<>(context.request().fileItems().values()).get(0); } else if (argType == ModelAndView.class) { return new ModelAndView(); } else if (argType == Map.class) { return context.request().parameters(); } else if (argType == Optional.class) { ParameterizedType firstParam = (ParameterizedType) parameter.getParameterizedType(); Type paramsOfFirstGeneric = firstParam.getActualTypeArguments()[0]; Class<?> modelType = ReflectKit.form(paramsOfFirstGeneric.getTypeName()); return Optional.ofNullable(parseModel(modelType, context.request(), null)); } else if (ParameterizedType.class.isInstance(argType)) { String name = parameter.getName(); List<String> values = context.request().parameters().get(name); return getParameterizedTypeValues(values, argType); } else if (ReflectKit.isArray(argType)) { List<String> values = context.request().parameters().get(paramName); if (null == values) { return null; return parseModel(ReflectKit.typeToClass(argType), context.request(), null);
/** * invoke hooks * * @param hooks webHook list * @param context http request * @return return invoke hook is abort */ private boolean invokeHook(List<Route> hooks, RouteContext context) throws Exception { for (Route hook : hooks) { if (hook.getTargetType() == RouteHandler.class) { RouteHandler routeHandler = (RouteHandler) hook.getTarget(); routeHandler.handle(context); if (context.isAbort()) { return false; } } else if (hook.getTargetType() == RouteHandler0.class) { RouteHandler0 routeHandler = (RouteHandler0) hook.getTarget(); routeHandler.handle(context.request(), context.response()); } else { boolean flag = this.invokeHook(context, hook); if (!flag) return false; } } return true; }
public static Object[] getRouteActionParameters(RouteContext context) { Method actionMethod = context.routeAction(); Request request = context.request(); actionMethod.setAccessible(true); Parameter[] parameters = actionMethod.getParameters(); Object[] args = new Object[parameters.length]; String[] parameterNames = ASMUtils.findMethodParmeterNames(actionMethod); for (int i = 0, len = parameters.length; i < len; i++) { Parameter parameter = parameters[i]; String paramName = Objects.requireNonNull(parameterNames)[i]; Type argType = parameter.getParameterizedType(); if (containsAnnotation(parameter)) { args[i] = getAnnotationParam(parameter, paramName, request); continue; } if (ReflectKit.isBasicType(argType)) { args[i] = request.query(paramName); continue; } args[i] = getCustomType(parameter, paramName, context); } return args; }
@Test public void testAuthSuccess() throws Exception { Request mockRequest = mockHttpRequest("GET"); WebContext.init(Blade.of(), "/"); Map<String, String> headers = new HashMap<>(); headers.put("Authorization", "Basic YWRtaW46MTIzNDU2"); when(mockRequest.parameters()).thenReturn(new HashMap<>()); when(mockRequest.headers()).thenReturn(headers); Request request = new HttpRequest(mockRequest); Response response = mockHttpResponse(200); RouteContext context = new RouteContext(request, response); context.initRoute(Route.builder() .action(AuthHandler.class.getMethod("handle", RouteContext.class)) .targetType(AuthHandler.class) .target(new AuthHandler()).build()); WebContext.set(new WebContext(request, response, null)); AuthOption authOption = AuthOption.builder().build(); authOption.addUser("admin", "123456"); BasicAuthMiddleware basicAuthMiddleware = new BasicAuthMiddleware(authOption); boolean flag = basicAuthMiddleware.before(context); assertTrue(flag); }
public static void main(String[] args) { Blade.of() .get("/hello", ctx -> ctx.text("get route")) .post("/post", ctx -> ctx.text(ctx.request().query("param","null"))) .webSocket("/websocket", new WebSocketHandler() { @Override public void onConnect(WebSocketContext ctx) { System.out.println("客户端连接上了ws1: " + ctx.getSession()); } @Override public void onText(WebSocketContext ctx) { System.out.println("ws1收到:" + ctx.getReqText()); ctx.message("发送: Hello"); } @Override public void onDisConnect(WebSocketContext ctx) { System.out.println("ws1客户端关闭链接: " + ctx.getSession()); } }).start(WebSocketDemo.class); }
@Override public boolean before(RouteContext context) { // 黑名单过滤 if (Utils.isBlackIP(context.address())) { context.text("You are forbidden to access :("); return false; } // 安装向导 if (!context.uri().startsWith("/install") && !Utils.isInstall()) { context.redirect("/install"); return false; } // 后台登录校验 if (context.uri().startsWith("/admin/") && !Utils.isLogin()) { context.redirect("/login"); return false; } return true; }
public RouteContext routeContext() { return new RouteContext(request, response); }
@Override public boolean before(RouteContext context) { if (csrfOption.isIgnoreMethod(context.method())) { if (csrfOption.isStartExclusion(context.uri())) { return true; } this.genToken(context); return true; } if (csrfOption.isExclusion(context.uri())) { return true; } String tokenUUID = context.session().attribute(sessionToken); if (StringKit.isEmpty(tokenUUID)) { csrfOption.getErrorHandler().accept(context); return false; } String token = csrfOption.getTokenGetter().apply(context.request()); if (StringKit.isEmpty(token)) { csrfOption.getErrorHandler().accept(context); return false; } String hash = new String(Base64.getDecoder().decode(token)); if (!PasswordKit.checkPassword(tokenUUID, hash)) { csrfOption.getErrorHandler().accept(context); return false; } return true; }
return context; } else if (argType == Request.class) { return context.request(); } else if (argType == Response.class) { return context.response(); } else if (argType == Session.class || argType == HttpSession.class) { return context.request().session(); } else if (argType == FileItem.class) { return new ArrayList<>(context.request().fileItems().values()).get(0); } else if (argType == ModelAndView.class) { return new ModelAndView(); } else if (argType == Map.class) { return context.request().parameters(); } else if (argType == Optional.class) { ParameterizedType firstParam = (ParameterizedType) parameter.getParameterizedType(); Type paramsOfFirstGeneric = firstParam.getActualTypeArguments()[0]; Class<?> modelType = ReflectKit.form(paramsOfFirstGeneric.getTypeName()); return Optional.ofNullable(parseModel(modelType, context.request(), null)); } else if (ParameterizedType.class.isInstance(argType)) { String name = parameter.getName(); List<String> values = context.request().parameters().get(name); return getParameterizedTypeValues(values, argType); } else if (ReflectKit.isArray(argType)) { List<String> values = context.request().parameters().get(paramName); if (null == values) { return null; return parseModel(ReflectKit.typeToClass(argType), context.request(), null);
/** * invoke hooks * * @param hooks webHook list * @param context http request * @return return invoke hook is abort */ private boolean invokeHook(List<Route> hooks, RouteContext context) throws Exception { for (Route hook : hooks) { if (hook.getTargetType() == RouteHandler.class) { RouteHandler routeHandler = (RouteHandler) hook.getTarget(); routeHandler.handle(context); if (context.isAbort()) { return false; } } else if (hook.getTargetType() == RouteHandler0.class) { RouteHandler0 routeHandler = (RouteHandler0) hook.getTarget(); routeHandler.handle(context.request(), context.response()); } else { boolean flag = this.invokeHook(context, hook); if (!flag) return false; } } return true; }
@Override public boolean before(RouteContext context) { boolean isAuth = false; for (String startExclusion : urlStartExclusions) { if ("/".equals(startExclusion) || context.uri().startsWith(startExclusion)) { isAuth = true; break; } } if (!isAuth) { return true; } String authorization = context.header("Authorization"); String user = this.searchCredential(authorization); if (null == user) { context.header("WWW-Authenticate", this.realm).status(401); return false; } return true; }
public static Object[] getRouteActionParameters(RouteContext context) { Method actionMethod = context.routeAction(); Request request = context.request(); actionMethod.setAccessible(true); Parameter[] parameters = actionMethod.getParameters(); Object[] args = new Object[parameters.length]; String[] parameterNames = ASMUtils.findMethodParmeterNames(actionMethod); for (int i = 0, len = parameters.length; i < len; i++) { Parameter parameter = parameters[i]; String paramName = Objects.requireNonNull(parameterNames)[i]; Type argType = parameter.getParameterizedType(); if (containsAnnotation(parameter)) { args[i] = getAnnotationParam(parameter, paramName, request); continue; } if (ReflectKit.isBasicType(argType)) { args[i] = request.query(paramName); continue; } args[i] = getCustomType(parameter, paramName, context); } return args; }