Java Code Examples for com.netflix.zuul.context.RequestContext#addZuulRequestHeader()
The following examples show how to use
com.netflix.zuul.context.RequestContext#addZuulRequestHeader() .
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: UserInfoHeaderFilter.java From microservices-platform with Apache License 2.0 | 6 votes |
@Override public Object run() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken)) { Object principal = authentication.getPrincipal(); RequestContext ctx = RequestContext.getCurrentContext(); //客户端模式只返回一个clientId if (principal instanceof SysUser) { SysUser user = (SysUser)authentication.getPrincipal(); ctx.addZuulRequestHeader(SecurityConstants.USER_ID_HEADER, String.valueOf(user.getId())); ctx.addZuulRequestHeader(SecurityConstants.USER_HEADER, user.getUsername()); } OAuth2Authentication oauth2Authentication = (OAuth2Authentication)authentication; String clientId = oauth2Authentication.getOAuth2Request().getClientId(); ctx.addZuulRequestHeader(SecurityConstants.TENANT_HEADER, clientId); ctx.addZuulRequestHeader(SecurityConstants.ROLE_HEADER, CollectionUtil.join(authentication.getAuthorities(), ",")); } return null; }
Example 2
Source File: IdFilter.java From demo-project with MIT License | 6 votes |
@Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); String id = ctx.getRequest().getHeader("id"); //如果request找不到,再到zuul的方法中找id.request不允许直接修改response中的header, // 所以为了让后续的过滤器能够获取到id才有下面的语法 if(id==null){ id = ctx.getZuulRequestHeaders().get("id"); } if (id == null) { id = UUID.randomUUID().toString(); LOGGER.info("{} 无id,生成id:{}",ctx.getRequest().getRequestURI(), id); ctx.addZuulRequestHeader("id", id); } else { LOGGER.info("{}存在id:{}", ctx.getRequest().getRequestURI(), id); } return null; }
Example 3
Source File: AuthFilter.java From xmfcn-spring-cloud with Apache License 2.0 | 6 votes |
@Override public Object run() { RequestContext requestContext = RequestContext.getCurrentContext(); HttpServletRequest request = requestContext.getRequest(); String requestUrl = request.getRequestURI(); String url = StringUtil.getSystemUrl(request); logger.info("请求requestUrl:"+requestUrl); logger.trace("请求url:"+url); //添加Basic Auth认证信息 if (requestUrl.contains("/server/")) { requestContext.addZuulRequestHeader("Authorization", "Basic " + getBase64Credentials(serviceName, servicePassword)); } else { requestContext.addZuulRequestHeader("Authorization", "Basic " + getBase64Credentials(apiName, apiPassword)); } requestContext.set("isSuccess", true);// 设值,让下一个Filter看到上一个Filter的状态 return null; }
Example 4
Source File: AccessFilter.java From pig with MIT License | 6 votes |
@Override public Object run() { RequestContext requestContext = RequestContext.getCurrentContext(); String version = requestContext.getRequest().getHeader(SecurityConstants.VERSION); if (canary && StrUtil.isNotBlank(version)) { RibbonVersionHolder.setContext(version); } requestContext.set("startTime", System.currentTimeMillis()); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null) { requestContext.addZuulRequestHeader(SecurityConstants.USER_HEADER, authentication.getName()); requestContext.addZuulRequestHeader(SecurityConstants.ROLE_HEADER, CollectionUtil.join(authentication.getAuthorities(), ",")); } return null; }
Example 5
Source File: UaaTokenRelayFilter.java From flair-registry with Apache License 2.0 | 5 votes |
@Override public Object run() throws ZuulException { RequestContext ctx = RequestContext.getCurrentContext(); // Add specific authorization headers for OAuth2 ctx.addZuulRequestHeader(AUTHORIZATION_HEADER, "Bearer " + oauth2clientCredentialsService.getAccessToken()); return null; }
Example 6
Source File: HttpBasicPassTicketSchemeTest.java From api-layer with Eclipse Public License 2.0 | 5 votes |
@Test void givenJwtInCookie_whenApply_thenJwtIsRemoved() { AuthenticationCommand command = getPassTicketCommand(); RequestContext requestContext = new RequestContext(); requestContext.addZuulRequestHeader("cookie", authConfigurationProperties.getCookieProperties().getCookieName() + "=jwt;" + "abc=def" ); RequestContext.testSetCurrentContext(requestContext); command.apply(null); String cookies = requestContext.getZuulRequestHeaders().get("cookie"); assertEquals("abc=def", cookies); }
Example 7
Source File: ZosmfScheme.java From api-layer with Eclipse Public License 2.0 | 5 votes |
private void removeCookie(RequestContext context, String name) { context.addZuulRequestHeader(COOKIE_HEADER, CookieUtil.removeCookie( context.getZuulRequestHeaders().get(COOKIE_HEADER), name ) ); }
Example 8
Source File: ZosmfScheme.java From api-layer with Eclipse Public License 2.0 | 5 votes |
private void setCookie(RequestContext context, String name, String value) { context.addZuulRequestHeader(COOKIE_HEADER, CookieUtil.setCookie( context.getZuulRequestHeaders().get(COOKIE_HEADER), name, value ) ); }
Example 9
Source File: CatHeaderFilter.java From piggymetrics with MIT License | 5 votes |
@Override public Object run() { // 保存和传递CAT调用链上下文 Context ctx = new CatContext(); Cat.logRemoteCallClient(ctx); RequestContext requestContext = RequestContext.getCurrentContext(); requestContext.addZuulRequestHeader(CatHttpConstants.CAT_HTTP_HEADER_ROOT_MESSAGE_ID, ctx.getProperty(Cat.Context.ROOT)); requestContext.addZuulRequestHeader(CatHttpConstants.CAT_HTTP_HEADER_PARENT_MESSAGE_ID, ctx.getProperty(Cat.Context.PARENT)); requestContext.addZuulRequestHeader(CatHttpConstants.CAT_HTTP_HEADER_CHILD_MESSAGE_ID, ctx.getProperty(Cat.Context.CHILD)); return null; }
Example 10
Source File: CustomPreZuulFilter.java From spring-security-oauth with MIT License | 5 votes |
@Override public Object run() { final RequestContext ctx = RequestContext.getCurrentContext(); logger.info("in zuul filter " + ctx.getRequest().getRequestURI()); byte[] encoded; try { encoded = Base64.getEncoder().encode("fooClientIdPassword:secret".getBytes("UTF-8")); ctx.addZuulRequestHeader("Authorization", "Basic " + new String(encoded)); logger.info("pre filter"); logger.info(ctx.getRequest().getHeader("Authorization")); final HttpServletRequest req = ctx.getRequest(); final String refreshToken = extractRefreshToken(req); if (refreshToken != null) { final Map<String, String[]> param = new HashMap<String, String[]>(); param.put("refresh_token", new String[] { refreshToken }); param.put("grant_type", new String[] { "refresh_token" }); ctx.setRequest(new CustomHttpServletRequest(req, param)); } } catch (final UnsupportedEncodingException e) { logger.error("Error occured in pre filter", e); } // return null; }
Example 11
Source File: HeimdallDecorationFilter.java From heimdall with Apache License 2.0 | 5 votes |
protected void addProxyHeaders(RequestContext ctx) { HttpServletRequest request = ctx.getRequest(); String host = toHostHeader(request); String port = String.valueOf(request.getServerPort()); String proto = request.getScheme(); if (hasHeader(request, X_FORWARDED_HOST_HEADER)) { host = request.getHeader(X_FORWARDED_HOST_HEADER) + "," + host; } if (!hasHeader(request, X_FORWARDED_PORT_HEADER)) { if (hasHeader(request, X_FORWARDED_PROTO_HEADER)) { StringBuilder builder = new StringBuilder(); for (String previous : StringUtils.commaDelimitedListToStringArray(request.getHeader(X_FORWARDED_PROTO_HEADER))) { if (builder.length() > 0) { builder.append(","); } builder.append(HTTPS_SCHEME.equals(previous) ? HTTPS_PORT : HTTP_PORT); } builder.append(",").append(port); port = builder.toString(); } } else { port = request.getHeader(X_FORWARDED_PORT_HEADER) + "," + port; } if (hasHeader(request, X_FORWARDED_PROTO_HEADER)) { proto = request.getHeader(X_FORWARDED_PROTO_HEADER) + "," + proto; } ctx.addZuulRequestHeader(X_FORWARDED_HOST_HEADER, host); ctx.addZuulRequestHeader(X_FORWARDED_PORT_HEADER, port); ctx.addZuulRequestHeader(X_FORWARDED_PROTO_HEADER, proto); }
Example 12
Source File: OAuth2TokenRelayFilter.java From flair-registry with Apache License 2.0 | 5 votes |
@Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); // Add specific authorization headers for OAuth2 ctx.addZuulRequestHeader(AUTHORIZATION_HEADER, AuthorizationHeaderUtil.getAuthorizationHeader()); return null; }
Example 13
Source File: TracePreZuulFilter.java From log-trace-spring-boot with Apache License 2.0 | 5 votes |
@Override public Object run() throws ZuulException { RequestContext context = RequestContext.getCurrentContext(); Map<String, String> copyOfContextMap = traceContentFactory.assemblyTraceContent(); for (Map.Entry<String, String> copyOfContext : copyOfContextMap.entrySet()) { context.addZuulRequestHeader(copyOfContext.getKey(), copyOfContext.getValue()); } log.debug("zuul traceid {}", MDC.get(Constants.LEGACY_TRACE_ID_NAME)); return null; }
Example 14
Source File: AddRequestHeaderFilter.java From Spring with Apache License 2.0 | 4 votes |
@Override public Object run() throws ZuulException { final RequestContext currentContext = RequestContext.getCurrentContext(); currentContext.addZuulRequestHeader("x-location", "USA"); return null; //return doesn't matter }
Example 15
Source File: PreFilter.java From NetworkDisk_Storage with GNU General Public License v2.0 | 4 votes |
@Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); ctx.addZuulRequestHeader("Authorization","Basic " + getBase64Credentials("admin","admin123")); HttpServletRequest request = ctx.getRequest(); String curOrigin = request.getHeader("Origin"); log.info(String.format("%s >>> %s >>> %s", request.getMethod(), request.getRequestURI(), curOrigin)); if (request.getRequestURI().contains("/api/user")) { if (request.getRequestURI().contains("logout") || request.getRequestURI().contains("changepwd") || request.getRequestURI().contains("loadimg") || request.getRequestURI().contains("uploadpic")) { verifyToken(ctx); } } if(request.getRequestURI().contains("/api/core")){ verifyToken(ctx); } //--------------------------------------------------------------------------------------------------------------------------------------- /*if (request.getRequestURI().contains("/regcheckusername") || request.getRequestURI().contains("/regcheckphone") || request.getRequestURI().contains("/getpass") || request.getRequestURI().contains("/css") || request.getRequestURI().contains("/js") || request.getRequestURI().contains("/css") || request.getRequestURI().contains("/images")) { ctx.setSendZuulResponse(true); return null; } InputStream in = (InputStream) ctx.get("requestEntity"); if (in == null) { in = ctx.getRequest().getInputStream(); } String token = null; if (request.getRequestURI().equals("/api/edge/getpublickey")) { ctx.setSendZuulResponse(true); return null; } if (!request.getRequestURI().contains("getverfyimg") && !request.getRequestURI().contains("regsmscodestr")) { if (!request.getContentType().contains("multipart/form-data")) { token = ctx.getRequest().getParameter("token"); } else { Part part = request.getPart("token"); InputStream name = part.getInputStream(); token = StreamUtils.copyToString(name, Charset.forName("UTF-8")); } } if (request.getRequestURI().equals("/api/user/logout") || request.getRequestURI().equals("/api/user/changepwd") || request.getRequestURI().equals("/api/user/uploadpic") || request.getRequestURI().equals("/api/user/loadimg")) { Claims claims = JWTUtils.parseJWT(token, "nimadetou".getBytes()); String subject = claims.getSubject(); Userinfo userinfo = JsonUtils.jsonToPojo(subject, Userinfo.class); log.info(userinfo.getUid()); ctx.setSendZuulResponse(true); return null; } else { ctx.setSendZuulResponse(true); return null; }*/ return null; }
Example 16
Source File: MyFilter.java From blog-examples with Apache License 2.0 | 4 votes |
@Override public Object run() { RequestContext context = RequestContext.getCurrentContext(); context.addZuulRequestHeader("my-auth-token", "s3cret"); return null; }
Example 17
Source File: AuthFilter.java From mini-platform with MIT License | 4 votes |
@Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); String uri = request.getRequestURI(); //忽略不需要授权的连接 if (ignoreServiceId.contains(uri.split("/")[1])){ return null; } String method = request.getMethod(); log.debug("------------------->pre Request:{}:{}",method, uri); //内部应用通过jwt_token访问后端服务 String jwtToken = request.getHeader("jwt_token"); if (StringUtils.isNotEmpty(jwtToken)) { return null; } //外部应用通过access_token访问后端服务,需要使用access_token在OAuth Server上换取jwtToken后传递给后方服务 String accessToken = request.getParameter("access_token"); if (StringUtils.isEmpty(accessToken)) { throw new BusinessException(ACCESS_TOKEN_ERROR); } try { jwtToken = tokenService.getJwtToken(accessToken); } catch (BusinessException e) { throw new BusinessException(e.getCode(), e.getMessage()); } if (StringUtils.isEmpty(jwtToken)) { throw new BusinessException(ACCESS_TOKEN_ERROR); } ctx.addZuulRequestHeader("jwtToken", jwtToken); return null; }
Example 18
Source File: HeimdallDecorationFilter.java From heimdall with Apache License 2.0 | 4 votes |
protected void process() { RequestContext ctx = RequestContext.getCurrentContext(); final String requestURI = getPathWithoutStripSuffix(ctx.getRequest()); if (pathMatcher.match(ConstantsPath.PATH_MANAGER_PATTERN, requestURI) || "/error".equals(requestURI)) { ctx.set(FORWARD_TO_KEY, requestURI); return; } final String method = ctx.getRequest().getMethod().toUpperCase(); HeimdallRoute heimdallRoute = getMatchingHeimdallRoute(requestURI, method, ctx); if (heimdallRoute != null) { if (heimdallRoute.isMethodNotAllowed()) { ctx.setSendZuulResponse(false); ctx.setResponseStatusCode(HttpStatus.METHOD_NOT_ALLOWED.value()); ctx.setResponseBody(HttpStatus.METHOD_NOT_ALLOWED.getReasonPhrase()); return; } if (heimdallRoute.getRoute() == null || heimdallRoute.getRoute().getLocation() == null) { log.warn("Environment not configured for this location: {} and inbound: {}", ctx.getRequest().getRequestURL(), requestURI); ctx.setSendZuulResponse(false); ctx.setResponseStatusCode(HttpStatus.FORBIDDEN.value()); ctx.setResponseBody("Environment not configured for this inbound"); ctx.getResponse().setContentType(MediaType.TEXT_PLAIN_VALUE); TraceContextHolder.getInstance().getActualTrace().setRequest(requestHelper.dumpRequest()); return; } String location = heimdallRoute.getRoute().getLocation(); ctx.put(REQUEST_URI_KEY, heimdallRoute.getRoute().getPath()); ctx.put(PROXY_KEY, heimdallRoute.getRoute().getId()); if (!heimdallRoute.getRoute().isCustomSensitiveHeaders()) { this.proxyRequestHelper.addIgnoredHeaders(this.properties.getSensitiveHeaders().toArray(new String[0])); } else { this.proxyRequestHelper.addIgnoredHeaders(heimdallRoute.getRoute().getSensitiveHeaders().toArray(new String[0])); } if (heimdallRoute.getRoute().getRetryable() != null) { ctx.put(RETRYABLE_KEY, heimdallRoute.getRoute().getRetryable()); } if (location.startsWith(HTTP_SCHEME + ":") || location.startsWith(HTTPS_SCHEME + ":")) { ctx.setRouteHost(UrlUtil.getUrl(location)); ctx.addOriginResponseHeader(SERVICE_HEADER, location); } else if (location.startsWith(FORWARD_LOCATION_PREFIX)) { ctx.set(FORWARD_TO_KEY, StringUtils.cleanPath(location.substring(FORWARD_LOCATION_PREFIX.length()) + heimdallRoute.getRoute().getPath())); ctx.setRouteHost(null); return; } else { // set serviceId for use in filters.route.RibbonRequest ctx.set(SERVICE_ID_KEY, location); ctx.setRouteHost(null); ctx.addOriginResponseHeader(SERVICE_ID_HEADER, location); } if (this.properties.isAddProxyHeaders()) { addProxyHeaders(ctx); String xforwardedfor = ctx.getRequest().getHeader(X_FORWARDED_FOR_HEADER); String remoteAddr = ctx.getRequest().getRemoteAddr(); if (xforwardedfor == null) { xforwardedfor = remoteAddr; } else if (!xforwardedfor.contains(remoteAddr)) { // Prevent duplicates xforwardedfor += ", " + remoteAddr; } ctx.addZuulRequestHeader(X_FORWARDED_FOR_HEADER, xforwardedfor); } if (this.properties.isAddHostHeader()) { ctx.addZuulRequestHeader(HttpHeaders.HOST, toHostHeader(ctx.getRequest())); } } else { log.warn("No route found for uri: " + requestURI); ctx.setSendZuulResponse(false); ctx.setResponseStatusCode(HttpStatus.NOT_FOUND.value()); ctx.setResponseBody(HttpStatus.NOT_FOUND.getReasonPhrase()); ctx.getResponse().setContentType(MediaType.TEXT_PLAIN_VALUE); TraceContextHolder.getInstance().getActualTrace().setRequest(requestHelper.dumpRequest()); } }
Example 19
Source File: FilterUtils.java From spring-microservices-in-action with Apache License 2.0 | 2 votes |
/** * Set the user ID to the header of a HTTP request. * * @param userId * The user ID needs to be set. */ public void setUserId(String userId){ RequestContext ctx = RequestContext.getCurrentContext(); ctx.addZuulRequestHeader(USER_ID, userId); }
Example 20
Source File: FilterUtils.java From spring-microservices-in-action with Apache License 2.0 | 2 votes |
/** * Set the organization ID to the header of a HTTP request. * * @param ordId * The organization ID needs to be set. */ public void setOrgId(String orgId){ RequestContext ctx = RequestContext.getCurrentContext(); ctx.addZuulRequestHeader(ORG_ID, orgId); }