Java Code Examples for javax.servlet.http.HttpServletRequest#getHeader()

The following examples show how to use javax.servlet.http.HttpServletRequest#getHeader() . 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: UserTaskManager.java    From cruise-control with BSD 2-Clause "Simplified" License 7 votes vote down vote up
/**
 * Method returns the user task id based on the {@link HttpServletRequest}. This method tries to find
 * the User-Task-ID from the request header and check if there is any UserTask with the same User-Task-ID.
 * If no User-Task-ID is passed then the {@link HttpSession} is used to fetch the User-Task-ID.
 *
 * @param httpServletRequest the HttpServletRequest to fetch the User-Task-ID and HTTPSession.
 * @return UUID of the user tasks or null if user task doesn't exist.
 */
public UUID getUserTaskId(HttpServletRequest httpServletRequest) {
  String userTaskIdString = httpServletRequest.getHeader(USER_TASK_HEADER_NAME);

  UUID userTaskId;
  if (userTaskIdString != null && !userTaskIdString.isEmpty()) { // valid user task id
    userTaskId = UUID.fromString(userTaskIdString);
  } else {
    SessionKey sessionKey = new SessionKey(httpServletRequest);
    synchronized (_sessionKeyToUserTaskIdMap) {
      userTaskId = _sessionKeyToUserTaskIdMap.get(sessionKey);
    }
  }

  return userTaskId;
}
 
Example 2
Source File: JwtAuthenticationTokenFilter.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * Attempt to authenticate request - basically just pass over to another method to authenticate request headers
 */
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {

    String header = request.getHeader(tokenHeader);
    if (header == null || !header.startsWith("Bearer ")) {
        throw new JwtTokenMissingException("No JWT token found in request headers");
    }
    String authToken = header.substring(7);

    if (SecurityContextHolder.getContext().getAuthentication() == null) {
        JwtAuthenticationToken authentication = new JwtAuthenticationToken(authToken);
        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }
    return SecurityContextHolder.getContext().getAuthentication();
}
 
Example 3
Source File: JwtService.java    From hauth-java with MIT License 6 votes vote down vote up
public static Authentication getAuthentication(HttpServletRequest request) {

        // 从Header中拿到token
        String token = request.getHeader(HEADER_STRING);
        if (token == null) {
            token = getTokenFromCookis(request);
        }

        if (token != null && !token.isEmpty()) {
            // 解析 Token
            Claims claims = Jwts.parser().setSigningKey(SECRET)
                    .parseClaimsJws(token).getBody();

            // 获取用户名
            String user = claims.get("UserId").toString();

            // 获取权限(角色)
            List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) claims.get("authorities"));

            // 返回验证令牌
            return user != null ? new UsernamePasswordAuthenticationToken(user, null, authorities) : null;
        }
        return null;
    }
 
Example 4
Source File: SpreadsheetUtil.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * Convenience method for setting the content-disposition:attachment header with escaping a file name.
 * @param response
 * @param fileName unescaped file name of the attachment
 */
protected static void setEscapedAttachmentHeader(final HttpServletResponse response, final String fileName) {
	String escapedFilename;
	try {
		escapedFilename = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
	} catch (UnsupportedEncodingException e) {
		escapedFilename = fileName;
	}

	FacesContext faces = FacesContext.getCurrentInstance();
	HttpServletRequest request = (HttpServletRequest) faces.getExternalContext().getRequest();
	String userAgent = request.getHeader("User-Agent");
	if (userAgent != null && userAgent.contains("MSIE")) {
		response.setHeader("Content-Disposition", "attachment" +
				((!StringUtils.isEmpty(escapedFilename)) ? ("; filename=\"" + escapedFilename + "\"") : ""));
	} else {
		response.setHeader("Content-Disposition", "attachment" +
				((!StringUtils.isEmpty(escapedFilename)) ? ("; filename*=utf-8''" + escapedFilename) : ""));
	}
}
 
Example 5
Source File: MomentController.java    From star-zone with Apache License 2.0 6 votes vote down vote up
@PostMapping("/like")
public ResponseData like(HttpServletRequest request, long momentId) {
    String userIdStr = request.getHeader("userId");
    log.info("MomentController.like__momentId={},userIdStr={}", new Object[]{momentId, userIdStr});
    momentLikeService.like(momentId, Long.valueOf(userIdStr));
    return ResponseData.newOK();
}
 
Example 6
Source File: FeignConfig.java    From microservice-recruit with Apache License 2.0 6 votes vote down vote up
@Bean
public RequestInterceptor headerInterceptor() {
    // 传递header
    return requestTemplate -> {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            Enumeration<String> headerNames = request.getHeaderNames();
            if (headerNames != null) {
                while (headerNames.hasMoreElements()) {
                    String name = headerNames.nextElement();
                    String values = request.getHeader(name);
                    requestTemplate.header(name, values);
                }
            }
        }
    };
}
 
Example 7
Source File: HttpRequestConfigTokenProvider.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
@Override
public String getToken() {
	HttpServletRequest request = httpRequest.getIfAvailable();
	if (request == null) {
		throw new IllegalStateException("No HttpServletRequest available");
	}

	String token = request.getHeader(ConfigClientProperties.TOKEN_HEADER);
	if (!StringUtils.hasLength(token)) {
		throw new IllegalArgumentException(
				"Missing required header in HttpServletRequest: "
						+ ConfigClientProperties.TOKEN_HEADER);
	}

	return token;
}
 
Example 8
Source File: HttpRequestDispatch.java    From vespa with Apache License 2.0 5 votes vote down vote up
private static RequestHandler wrapHandlerIfFormPost(RequestHandler requestHandler,
                                                    HttpServletRequest servletRequest,
                                                    boolean removeBodyForFormPost) {
    if (!servletRequest.getMethod().equals("POST")) {
        return requestHandler;
    }
    String contentType = servletRequest.getHeader(HttpHeaders.Names.CONTENT_TYPE);
    if (contentType == null) {
        return requestHandler;
    }
    if (!contentType.startsWith(APPLICATION_X_WWW_FORM_URLENCODED)) {
        return requestHandler;
    }
    return new FormPostRequestHandler(requestHandler, getCharsetName(contentType), removeBodyForFormPost);
}
 
Example 9
Source File: HeaderSiteResolver.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String getSiteName(HttpServletRequest request) {
    String siteName = request.getHeader(headerName);
    if (StringUtils.isEmpty(siteName)) {
        logger.debug("No '{}' request header found", headerName);
    }

    return siteName;
}
 
Example 10
Source File: IPUtils.java    From newblog with Apache License 2.0 5 votes vote down vote up
public static String getIpAddr(HttpServletRequest request) {
    String ip = request.getHeader("x-forwarded-for");
    if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
        // 多次反向代理后会有多个ip值,第一个ip才是真实ip
        if (ip.indexOf(",") != -1) {
            ip = ip.split(",")[0];
        }
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("HTTP_CLIENT_IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("HTTP_X_FORWARDED_FOR");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("X-Real-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getRemoteAddr();
    }
    return ip;
}
 
Example 11
Source File: AnalyzeResourceWithFactsImpl.java    From ambiverse-nlu with Apache License 2.0 5 votes vote down vote up
private static String getCallerIp(HttpServletRequest req) {
  String ip = req.getRemoteAddr();
  // Make sure to get the actual IP of the requester if
  // the service works behind a gateway.
  String forward = req.getHeader("X-Forwarded-For");
  if (forward != null) {
    ip = forward;
  }
  return ip;
}
 
Example 12
Source File: BearerSecurityContextRepository.java    From auth0-spring-security-api with MIT License 5 votes vote down vote up
private String tokenFromRequest(HttpServletRequest request) {
    final String value = request.getHeader("Authorization");

    if (value == null || !value.toLowerCase().startsWith("bearer")) {
        return null;
    }

    String[] parts = value.split(" ");

    if (parts.length < 2) {
        return null;
    }

    return parts[1].trim();
}
 
Example 13
Source File: WebUtil.java    From anyline with Apache License 2.0 5 votes vote down vote up
/**
 * 判断是否是ajax请求
 *
 * @param request  request
 * @return return
 */
public static boolean isAjaxRequest(HttpServletRequest request) {
	String header = request.getHeader("x-requested-with");
	if (header != null && "XMLHttpRequest".equals(header)) {
		return true;
	}
	return false;
}
 
Example 14
Source File: JwtAuthenticationFilter.java    From Spring-Boot-Blog-REST-API with GNU Affero General Public License v3.0 5 votes vote down vote up
private String getJwtFromRequest(HttpServletRequest request){
    String bearerToken = request.getHeader("Authorization");
    if(StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")){
        return bearerToken.substring(7, bearerToken.length());
    }
    return null;
}
 
Example 15
Source File: MyAuthenticationSucessHandler.java    From SpringAll with MIT License 5 votes vote down vote up
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
    // 1. 从请求头中获取 ClientId
    String header = request.getHeader("Authorization");
    if (header == null || !header.startsWith("Basic ")) {
        throw new UnapprovedClientAuthenticationException("请求头中无client信息");
    }

    String[] tokens = this.extractAndDecodeHeader(header, request);
    String clientId = tokens[0];
    String clientSecret = tokens[1];

    TokenRequest tokenRequest = null;

    // 2. 通过 ClientDetailsService 获取 ClientDetails
    ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);

    // 3. 校验 ClientId和 ClientSecret的正确性
    if (clientDetails == null) {
        throw new UnapprovedClientAuthenticationException("clientId:" + clientId + "对应的信息不存在");
    } else if (!passwordEncoder.matches(clientSecret, clientDetails.getClientSecret())) {
        throw new UnapprovedClientAuthenticationException("clientSecret不正确");
    } else {
        // 4. 通过 TokenRequest构造器生成 TokenRequest
        tokenRequest = new TokenRequest(new HashMap<>(), clientId, clientDetails.getScope(), "custom");
    }

    // 5. 通过 TokenRequest的 createOAuth2Request方法获取 OAuth2Request
    OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
    // 6. 通过 Authentication和 OAuth2Request构造出 OAuth2Authentication
    OAuth2Authentication auth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);

    // 7. 通过 AuthorizationServerTokenServices 生成 OAuth2AccessToken
    OAuth2AccessToken token = authorizationServerTokenServices.createAccessToken(auth2Authentication);

    // 8. 返回 Token
    log.info("登录成功");
    response.setContentType("application/json;charset=UTF-8");
    response.getWriter().write(new ObjectMapper().writeValueAsString(token));
}
 
Example 16
Source File: RequestParameters.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * Returns first HTTP header associated with {@code name}.
 *
 * @param name case insensitive header name
 * @throws BadRequestException if request header is absent or empty
 */
public static String extractRequiredHeader(HttpServletRequest req, String name) {
  String result = req.getHeader(name);
  if (isNullOrEmpty(result)) {
    throw new BadRequestException("Missing header: " + name);
  }
  return result;
}
 
Example 17
Source File: GenericFileHandler.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Handles If-Match header precondition
 *
 * @param request The HTTP request object
 * @param response The servlet response object
 * @param etag The file's ETag
 * @return {@code true} if the If-Match header precondition failed (doesn't match the file's ETag), {@code false} otherwise
 */
protected boolean handleIfMatchHeader(HttpServletRequest request, HttpServletResponse response, String etag) {
	String ifMatchHeader = request.getHeader(ProtocolConstants.HEADER_IF_MATCH);
	if (ifMatchHeader != null && !ifMatchHeader.equals(etag)) {
		response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
		return true;
	}
	return false;
}
 
Example 18
Source File: IPResolver.java    From development with Apache License 2.0 5 votes vote down vote up
public static String resolveIpAddress(HttpServletRequest request) {
    Enumeration<?> headerNames = request.getHeaderNames();
    if (headerNames != null) {
        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            if (headerName.equalsIgnoreCase("x-forwarded-for")) {
                String ipAddress = request.getHeader(headerName);
                if (ipAddress != null && ipAddress.trim().length() > 0) {
                    return ipAddress;
                }
            }
        }
    }
    return request.getRemoteAddr();
}
 
Example 19
Source File: GoogleAuthorizationRequestServlet.java    From spring-security-jwt with MIT License 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String state = xsrfUtils.newToken();
    request.getSession().setAttribute(XsrfUtils.XSRF_KEY, state);

    // todo https://developers.google.com/accounts/docs/OpenIDConnect#discovery
    String location = "https://accounts.google.com/o/oauth2/auth"
            + "?client_id=" + appConfig.getGoogleClientId()
            + "&response_type=code"
            + "&scope=openid%20email"
            + "&redirect_uri=" + request.getHeader("Referer") + "auth/google/response"
            + "&state=" + state;

    response.sendRedirect(location);
}
 
Example 20
Source File: MomentController.java    From star-zone with Apache License 2.0 4 votes vote down vote up
@PostMapping("/delete")
public ResponseData delete(HttpServletRequest request, long id) {
    String userIdStr = request.getHeader("userId");
    momentService.delete(id, Long.valueOf(userIdStr));
    return ResponseData.newOK();
}