Java Code Examples for io.vertx.ext.web.RoutingContext#session()
The following examples show how to use
io.vertx.ext.web.RoutingContext#session() .
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: AdminLoginHandler.java From joyqueue with Apache License 2.0 | 6 votes |
@Override public void handle(final RoutingContext context) { HttpServerRequest request = context.request(); Session session = context.session(); if (session == null) { context.fail(new HttpStatusException(HTTP_INTERNAL_ERROR, "No session - did you forget to include a SessionHandler?")); return; } String remoteIP = getRemoteIP(request); context.put(REMOTE_IP, remoteIP); User user = session.get(userSessionKey); if (user == null) { user = userService.findByCode(DEFAULT_LOGIN_USER_CODE); } //存放用户上下文信息 context.put(USER_KEY, user); context.next(); }
Example 2
Source File: SummerRouter.java From Summer with MIT License | 6 votes |
private Object getContext(RoutingContext routingContext,ArgInfo argInfo){ Class clz = argInfo.getClazz(); if (clz ==RoutingContext.class){ return routingContext; }else if (clz == HttpServerRequest.class){ return routingContext.request(); }else if (clz == HttpServerResponse.class){ return routingContext.response(); }else if (clz == Session.class){ return routingContext.session(); }else if (clz == Vertx.class){ return vertx; } return null; }
Example 3
Source File: RedirectAuthHandlerImpl.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Override public void parseCredentials(RoutingContext context, Handler<AsyncResult<JsonObject>> handler) { Session session = context.session(); if (session != null) { try { // Save current request in session - we'll get redirected back here after successful login io.vertx.reactivex.core.http.HttpServerRequest request = new io.vertx.reactivex.core.http.HttpServerRequest(context.request()); Map<String, String> requestParameters = request.params().entries().stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); session.put(returnURLParam, UriBuilderRequest.resolveProxyRequest(request, request.path(), requestParameters)); // Now redirect to the login url String uri = UriBuilderRequest.resolveProxyRequest(request, loginRedirectURL, requestParameters, true); handler.handle(Future.failedFuture(new HttpStatusException(302, uri))); } catch (Exception e) { logger.warn("Failed to decode login redirect url", e); handler.handle(Future.failedFuture(new HttpStatusException(302, loginRedirectURL))); } } else { handler.handle(Future.failedFuture("No session - did you forget to include a SessionHandler?")); } }
Example 4
Source File: SockJSSession.java From vertx-web with Apache License 2.0 | 6 votes |
SockJSSession(Vertx vertx, LocalMap<String, SockJSSession> sessions, RoutingContext rc, String id, long timeout, long heartbeatInterval, Handler<SockJSSocket> sockHandler) { super(vertx, rc.session(), rc.user()); this.sessions = sessions; this.id = id; this.timeout = timeout; this.sockHandler = sockHandler; context = vertx.getOrCreateContext(); pendingReads = new InboundBuffer<>(context); // Start a heartbeat heartbeatID = vertx.setPeriodic(heartbeatInterval, tid -> { if (listener != null) { listener.sendFrame("h", null); } }); }
Example 5
Source File: DigestAuthHandlerImpl.java From vertx-web with Apache License 2.0 | 6 votes |
@Override public String authenticateHeader(RoutingContext context) { final byte[] bytes = new byte[32]; random.nextBytes(bytes); // generate nonce String nonce = md5(bytes); // save it nonces.put(nonce, new Nonce(0)); // generate opaque String opaque = null; final Session session = context.session(); if (session != null) { opaque = (String) session.data().get("opaque"); } if (opaque == null) { random.nextBytes(bytes); // generate random opaque opaque = md5(bytes); } return "Digest realm=\"" + realm + "\", qop=\"auth\", nonce=\"" + nonce + "\", opaque=\"" + opaque + "\""; }
Example 6
Source File: CSRFHandlerImpl.java From vertx-web with Apache License 2.0 | 6 votes |
private String getTokenFromSession(RoutingContext ctx) { Session session = ctx.session(); if (session == null) { return null; } // get the token from the session String sessionToken = session.get(headerName); if (sessionToken != null) { // attempt to parse the value int idx = sessionToken.indexOf('/'); if (idx != -1 && session.id() != null && session.id().equals(sessionToken.substring(0, idx))) { return sessionToken.substring(idx + 1); } } // fail return null; }
Example 7
Source File: ContextParameterResolver.java From festival with Apache License 2.0 | 5 votes |
@Override protected Object doResolve(Parameter parameter, RoutingContext routingContext) { Class<?> parameterType = parameter.getType(); if (parameterType == RoutingContext.class) { return routingContext; } if (parameterType == HttpServerRequest.class) { return routingContext.request(); } if (parameterType == HttpServerResponse.class) { return routingContext.response(); } if (parameterType == Session.class) { return routingContext.session(); } if (parameterType == MultiMap.class) { return resolveParams(routingContext); } if (parameterType == JsonObject.class) { JsonObject jsonObject = routingContext.getBodyAsJson(); return jsonObject == null ? new JsonObject() : jsonObject; } return null; }
Example 8
Source File: TestSessionRest.java From rest.vertx with Apache License 2.0 | 5 votes |
@GET @Path("/echo") @Produces(MediaType.TEXT_HTML) public String echo(@Context RoutingContext routingContext) { Session session = routingContext.session(); return session.id(); }
Example 9
Source File: VxApiAuthSessionTokenImpl.java From VX-API-Gateway with MIT License | 5 votes |
@Override public void handle(RoutingContext event) { Session session = event.session(); if (session == null) { if (!event.response().ended()) { event.response().putHeader(HttpHeaderConstant.SERVER, VxApiGatewayAttribute.FULL_NAME) .putHeader(HttpHeaderConstant.CONTENT_TYPE, authFailContentType.val()).end(authFailResult); } } else { // session中的token String apiToken = session.get(apiTokenName) == null ? null : session.get(apiTokenName).toString(); // 用户request中的token String userTokoen = null; if (userTokenScope == ParamPositionEnum.HEADER) { userTokoen = event.request().getHeader(userTokenName); } else { userTokoen = event.request().getParam(userTokenName); } // 检验请求是否正确如果正确放行反则不通过 if (!StrUtil.isNullOrEmpty(apiToken) && apiToken.equals(userTokoen)) { event.next(); } else { if (!event.response().ended()) { event.response().putHeader(HttpHeaderConstant.SERVER, VxApiGatewayAttribute.FULL_NAME) .putHeader(HttpHeaderConstant.CONTENT_TYPE, authFailContentType.val()).end(authFailResult); } } } }
Example 10
Source File: RedirectAuthHandlerImpl.java From vertx-web with Apache License 2.0 | 5 votes |
@Override public void parseCredentials(RoutingContext context, Handler<AsyncResult<Credentials>> handler) { Session session = context.session(); if (session != null) { // Now redirect to the login url - we'll get redirected back here after successful login session.put(returnURLParam, context.request().uri()); handler.handle(Future.failedFuture(new HttpStatusException(302, loginRedirectURL))); } else { handler.handle(Future.failedFuture("No session - did you forget to include a SessionHandler?")); } }
Example 11
Source File: FormLoginHandlerImpl.java From graviteeio-access-management with Apache License 2.0 | 4 votes |
@Override public void handle(RoutingContext context) { HttpServerRequest req = context.request(); if (req.method() != HttpMethod.POST) { context.fail(405); // Must be a POST } else { if (!req.isExpectMultipart()) { throw new IllegalStateException("Form body not parsed - do you forget to include a BodyHandler?"); } MultiMap params = req.formAttributes(); String username = params.get(usernameParam); String password = params.get(passwordParam); String clientId = params.get(Parameters.CLIENT_ID); if (username == null || password == null) { log.warn("No username or password provided in form - did you forget to include a BodyHandler?"); context.fail(400); } else if (clientId == null) { log.warn("No client id in form - did you forget to include client_id query parameter ?"); context.fail(400); } else { Session session = context.session(); // build authentication object with ip address and user agent JsonObject authInfo = new JsonObject() .put("username", username) .put("password", password) .put(Claims.ip_address, remoteAddress(req)) .put(Claims.user_agent, userAgent(req)) .put(Parameters.CLIENT_ID, clientId); authProvider.authenticate(context, authInfo, res -> { if (res.succeeded()) { User user = res.result(); context.setUser(user); if (session != null) { // the user has upgraded from unauthenticated to authenticated // session should be upgraded as recommended by owasp session.regenerateId(); // Note : keep returnURLParam in session in case the user go to previous page // String returnURL = session.remove(returnURLParam); String returnURL = session.get(returnURLParam); if (returnURL != null) { // Now redirect back to the original url doRedirect(req.response(), returnURL); return; } } // Either no session or no return url if (directLoggedInOKURL != null) { // Redirect to the default logged in OK page - this would occur // if the user logged in directly at this URL without being redirected here first from another // url doRedirect(req.response(), directLoggedInOKURL); } else { // Just show a basic page req.response().end(DEFAULT_DIRECT_LOGGED_IN_OK_PAGE); } } else { handleException(context); } }); } } }
Example 12
Source File: SessionParamInjector.java From nubes with Apache License 2.0 | 4 votes |
@Override public Session resolve(RoutingContext context) { return context.session(); }
Example 13
Source File: FormLoginHandlerImpl.java From vertx-web with Apache License 2.0 | 4 votes |
@Override public void handle(RoutingContext context) { HttpServerRequest req = context.request(); if (req.method() != HttpMethod.POST) { context.fail(405); // Must be a POST } else { if (!req.isExpectMultipart()) { throw new IllegalStateException("HttpServerRequest should have setExpectMultipart set to true, but it is currently set to false."); } MultiMap params = req.formAttributes(); String username = params.get(usernameParam); String password = params.get(passwordParam); if (username == null || password == null) { log.warn("No username or password provided in form - did you forget to include a BodyHandler?"); context.fail(400); } else { Session session = context.session(); UsernamePasswordCredentials authInfo = new UsernamePasswordCredentials(username, password); authProvider.authenticate(authInfo, res -> { if (res.succeeded()) { User user = res.result(); context.setUser(user); if (session != null) { // the user has upgraded from unauthenticated to authenticated // session should be upgraded as recommended by owasp session.regenerateId(); String returnURL = session.remove(returnURLParam); if (returnURL != null) { // Now redirect back to the original url doRedirect(req.response(), returnURL); return; } } // Either no session or no return url if (directLoggedInOKURL != null) { // Redirect to the default logged in OK page - this would occur // if the user logged in directly at this URL without being redirected here first from another // url doRedirect(req.response(), directLoggedInOKURL); } else { // Just show a basic page req.response().end(DEFAULT_DIRECT_LOGGED_IN_OK_PAGE); } } else { context.fail(401); // Failed login } }); } } }
Example 14
Source File: CSRFHandlerImpl.java From vertx-web with Apache License 2.0 | 4 votes |
@Override public void handle(RoutingContext ctx) { if (nagHttps) { String uri = ctx.request().absoluteURI(); if (uri != null && !uri.startsWith("https:")) { log.trace("Using session cookies without https could make you susceptible to session hijacking: " + uri); } } HttpMethod method = ctx.request().method(); Session session = ctx.session(); // if we're being strict with the origin // ensure that they are always valid if (!isValidOrigin(ctx)) { ctx.fail(403); return; } switch (method.name()) { case "GET": final String token; if (session == null) { // if there's no session to store values, tokens are issued on every request token = generateAndStoreToken(ctx); } else { // get the token from the session, this also considers the fact // that the token might be invalid as it was issued for a previous session id // session id's change on session upgrades (unauthenticated -> authenticated; role change; etc...) String sessionToken = getTokenFromSession(ctx); // when there's no token in the session, then we behave just like when there is no session // create a new token, but we also store it in the session for the next runs if (sessionToken == null) { token = generateAndStoreToken(ctx); // storing will include the session id too. The reason is that if a session is upgraded // we don't want to allow the token to be valid anymore session.put(headerName, session.id() + "/" + token); } else { String[] parts = sessionToken.split("\\."); final long ts = parseLong(parts[1]); if (ts == -1) { // fallback as the token is expired token = generateAndStoreToken(ctx); } else { if (!(System.currentTimeMillis() > ts + timeout)) { // we're still on the same session, no need to regenerate the token // also note that the token isn't expired, so it can be reused token = sessionToken; // in this case specifically we don't issue the token as it is unchanged // the user agent still has it from the previous interaction. } else { // fallback as the token is expired token = generateAndStoreToken(ctx); } } } } // put the token in the context for users who prefer to render the token directly on the HTML ctx.put(headerName, token); ctx.next(); break; case "POST": case "PUT": case "DELETE": case "PATCH": if (isValidRequest(ctx)) { // it matches, so refresh the token to avoid replay attacks token = generateAndStoreToken(ctx); // put the token in the context for users who prefer to // render the token directly on the HTML ctx.put(headerName, token); ctx.next(); } else { ctx.fail(403); } break; default: // ignore other methods ctx.next(); break; } }