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

The following are Jave code examples for showing how to use getHeader() of the javax.servlet.http.HttpServletRequest class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: MicroServiceDemo   File: JwtTokenUtil.java   View Source Code Vote up 10 votes
public Authentication getAuthentication(HttpServletRequest request) {
    String token = request.getHeader(HEADER_STRING);
    if (token != null) {
        // parse the token.
        String user = getUsername(token);

        String roles = getBody(token).get("roles", String.class);
        List<GrantedAuthority> grantedAuths =
                AuthorityUtils.commaSeparatedStringToAuthorityList(roles);

        return user != null ?
                new UsernamePasswordAuthenticationToken(user, null,
                        grantedAuths) :
                null;
    }
    return null;
}
 
Example 2
Project: ServiceServer   File: CORSFilter.java   View Source Code Vote up 6 votes
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest)request;
    String ori = req.getHeader("Origin");
    if (ori != null && allowedOrigins.contains(ori)) {
        HttpServletResponse res = (HttpServletResponse)response;
        res.setHeader("Access-Control-Allow-Origin", ori);
        res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        res.setHeader("Access-Control-Max-Age", "3600");
        res.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        res.setHeader("Access-Control-Allow-Credentials", "true");
    }
    chain.doFilter(request, response);
}
 
Example 3
Project: uroborosql-springboot-demo   File: AuthInterceptor.java   View Source Code Vote up 6 votes
@Override
public boolean preHandle(HttpServletRequest request,
                         HttpServletResponse response, Object object) throws Exception {
    String authHeader = request.getHeader("authorization");

    if (!"OPTIONS".equals(request.getMethod())) {
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            throw new JwtAuthException();
        }

        String token = authHeader.substring(7);

        try {
            Claims claims = Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(token)
                .getBody();
            AuthContext.addClaims(claims);
        } catch (Exception e) {
            LOG.error("JWT parse error.", e);
            throw new JwtAuthException(e);
        }
    }

    return true;
}
 
Example 4
Project: CampusHelp   File: MyInterceptor.java   View Source Code Vote up 6 votes
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    logger.debug(request.getRequestURI());
    if ("campus".equals(request.getHeader("accept-type"))) {
        if (!StringUtils.isEmpty(request.getHeader("token"))) {
            String token = request.getHeader("token");
            try {
                long endTime = tokenDao.getEndTime(token);
                long currentTime = System.currentTimeMillis() / 1000L;
                if (currentTime > endTime) {
                    response.getWriter().write("{code:300}");
                    return false;
                }
            } catch (Exception e) {
                response.setStatus(403);
                return false;
            }
        }
    } else {
        response.setStatus(403);
        return false;
    }
    logger.debug("preHandle");
    return true;
}
 
Example 5
Project: Practical-Microservices   File: JwtAuthenticationTokenFilter.java   View Source Code Vote up 6 votes
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
		throws IOException, ServletException {
	HttpServletRequest httpServletRequest = (HttpServletRequest) request;

	String header_authorization = httpServletRequest.getHeader("Authorization");
	String token = (StringUtils.isBlank(header_authorization) ? null : header_authorization.split(" ")[1]);

	if (StringUtils.isBlank(header_authorization) && token == null) {
		logger.info("Token Not found in header.");
	} else {

		UserDetails principal = null;
		try {
			principal = authBuilder.getDefaultUserDetailsService().loadUserByUsername(token);
			UsernamePasswordAuthenticationToken userAuthenticationToken = new UsernamePasswordAuthenticationToken(
					principal, "", principal.getAuthorities());
			userAuthenticationToken
					.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
			SecurityContextHolder.getContext().setAuthentication(userAuthenticationToken);
		} catch (Exception e) {
			HttpServletResponse httpresposne = (HttpServletResponse) response;
			httpresposne.setContentType("application/json");
			httpresposne.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
			ObjectMapper jsonMapper = new ObjectMapper();
			PrintWriter out = httpresposne.getWriter();
			Map<String, String> jsonResponse = new HashMap<String, String>();
			jsonResponse.put("msg", "Invalid Token");
			out.write(jsonMapper.writeValueAsString(jsonResponse));
			out.flush();
			out.close();
			return;
		}
		chain.doFilter(request, response);
	}
}
 
Example 6
Project: sucok-framework   File: WebUtils.java   View Source Code Vote up 5 votes
private static String getUsetAgent() {
	HttpServletRequest request = getCurrentRequest();
	if (request == null) {
		return null;
	}
	return request.getHeader("user-agent");
}
 
Example 7
Project: pds   File: AuthorizationInterceptor.java   View Source Code Vote up 5 votes
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    IgnoreAuth annotation;
    if(handler instanceof HandlerMethod) {
        annotation = ((HandlerMethod) handler).getMethodAnnotation(IgnoreAuth.class);
    }else{
        return true;
    }

    //如果有@IgnoreAuth注解,则不验证token
    if(annotation != null){
        return true;
    }

    //从header中获取token
    String token = request.getHeader("token");
    //如果header中不存在token,则从参数中获取token
    if(StringUtils.isBlank(token)){
        token = request.getParameter("token");
    }

    //token为空
    if(StringUtils.isBlank(token)){
        throw new RRException("token不能为空");
    }

    //查询token信息
    TokenEntity tokenEntity = tokenService.queryByToken(token);
    if(tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()){
        throw new RRException("token失效,请重新登录");
    }

    //设置userId到request里,后续根据userId,获取用户信息
    request.setAttribute(LOGIN_USER_KEY, tokenEntity.getUserId());

    return true;
}
 
Example 8
Project: spring-cloud-gcp   File: XCloudTraceIdExtractor.java   View Source Code Vote up 5 votes
@Override
public String extractTraceIdFromRequest(HttpServletRequest req) {
	String traceId = req.getHeader(X_CLOUD_TRACE_HEADER);

	if (traceId != null) {
		int slash = traceId.indexOf('/');
		if (slash >= 0) {
			traceId = traceId.substring(0, slash);
		}
	}
	return traceId;
}
 
Example 9
Project: tour-of-heros-api-security-zerhusen   File: AuthenticationRestController.java   View Source Code Vote up 5 votes
@RequestMapping(value = "${jwt.route.authentication.refresh}", method = RequestMethod.GET)
public ResponseEntity<?> refreshAndGetAuthenticationToken(HttpServletRequest request) {
    String token = request.getHeader(tokenHeader);
    String username = jwtTokenUtil.getUsernameFromToken(token);
    JwtUser user = (JwtUser) userDetailsService.loadUserByUsername(username);

    if (jwtTokenUtil.canTokenBeRefreshed(token, user.getLastPasswordResetDate())) {
        String refreshedToken = jwtTokenUtil.refreshToken(token);
        return ResponseEntity.ok(new JwtAuthenticationResponse(refreshedToken));
    } else {
        return ResponseEntity.badRequest().body(null);
    }
}
 
Example 10
Project: aws-xray-sdk-java   File: AWSXRayServletFilter.java   View Source Code Vote up 5 votes
private Optional<String> getUserAgent(HttpServletRequest request) {
    String userAgentHeaderString = request.getHeader("User-Agent");
    if (null != userAgentHeaderString) {
        return Optional.of(userAgentHeaderString);
    }
    return Optional.empty();
}
 
Example 11
Project: automat   File: CsrfFilter.java   View Source Code Vote up 5 votes
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
		throws IOException, ServletException {
	try {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		// 获取请求url地址
		String url = req.getRequestURL().toString();
		String referurl = req.getHeader("Referer");
		if (isWhiteReq(referurl)) {
			chain.doFilter(request, response);
		} else {
			req.getRequestDispatcher("/").forward(req, res);

			// 记录跨站请求日志
			String log = "";
			String date = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
			String clientIp = WebUtil.getHost(req);

			log = "跨站请求---->>>" + clientIp + "||" + date + "||" + referurl + "||" + url;
			logger.warn(log);
			return;
		}

	} catch (Exception e) {
		logger.error("doFilter", e);
	}

}
 
Example 12
Project: SSM-DUBBO-HTTP   File: DubboController.java   View Source Code Vote up 5 votes
/**
 * 获取IP
 * @param request
 * @return
 */
private String getIP(HttpServletRequest request) {
    if (request == null)
        return null;
    String s = request.getHeader("X-Forwarded-For");
    if (s == null || s.length() == 0 || "unknown".equalsIgnoreCase(s)) {

        s = request.getHeader("Proxy-Client-IP");
    }
    if (s == null || s.length() == 0 || "unknown".equalsIgnoreCase(s)) {

        s = request.getHeader("WL-Proxy-Client-IP");
    }
    if (s == null || s.length() == 0 || "unknown".equalsIgnoreCase(s)) {
        s = request.getHeader("HTTP_CLIENT_IP");
    }
    if (s == null || s.length() == 0 || "unknown".equalsIgnoreCase(s)) {

        s = request.getHeader("HTTP_X_FORWARDED_FOR");
    }
    if (s == null || s.length() == 0 || "unknown".equalsIgnoreCase(s)) {

        s = request.getRemoteAddr();
    }
    if ("127.0.0.1".equals(s) || "0:0:0:0:0:0:0:1".equals(s))
        try {
            s = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException unknownhostexception) {
            return "";
        }
    return s;
}
 
Example 13
Project: sso-client   File: Urls.java   View Source Code Vote up 5 votes
public static String getServerBaseUrl(final HttpServletRequest request){
    String schema=request.getHeader("x-forwarded-proto");
    if(schema==null || "".equals(schema)){
        schema=request.getScheme();
    }
    schema+="://";
    String host =request.getHeader("x-forwarded-host");
    if(host==null || "".equals(host)){
        host=request.getServerName() + ":" + request.getServerPort();
    }
    String url=schema+host;
    url=regularUrl(url);

    return url;
}
 
Example 14
Project: BackOffice   File: PlantainController.java   View Source Code Vote up 5 votes
private Map<String, String> getHeadersInfo(HttpServletRequest request) {
    Map<String, String> map = new HashMap<>();
    Enumeration headerNames = request.getHeaderNames();
    LOG.info("Headers: ");
    while (headerNames.hasMoreElements()) {
        String key = (String) headerNames.nextElement();
        String value = request.getHeader(key);
        LOG.info("name: " + key + "      |      value: " + value);
        map.put(key, value);
    }
    return map;
}
 
Example 15
Project: Equella   File: OAuthUserStateHook.java   View Source Code Vote up 5 votes
@SuppressWarnings("nls")
@Override
public UserStateResult getUserState(HttpServletRequest request, UserState existingUserState) throws WebException
{
	// X-Authorization header
	final String xauth = request.getHeader(OAuthWebConstants.HEADER_X_AUTHORIZATION);
	if( xauth != null )
	{
		// should be "access_token=hghjghjghjg"
		final String[] token = xauth.split("=");
		if( token[0].equals(OAuthWebConstants.AUTHORIZATION_ACCESS_TOKEN) )
		{
			if( token.length == 2 )
			{
				final String tokenData = token[1];
				return userStateFromToken(request, tokenData, false);
			}
			throw new WebException(403, OAuthConstants.ERROR_ACCESS_DENIED,
				"Invalid access_token format in X-Authorization header");
		}
	}

	// Query string param
	final String tokenParamValue = request.getParameter(OAuthWebConstants.AUTHORIZATION_ACCESS_TOKEN);
	if( !Strings.isNullOrEmpty(tokenParamValue) )
	{
		return userStateFromToken(request, tokenParamValue, true);
	}

	return null;
}
 
Example 16
Project: java-web-services-training   File: JwtAuthFilter.java   View Source Code Vote up 5 votes
@Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (request instanceof HttpServletRequest) {
            boolean allowed = true;
            HttpServletRequest httpReq = (HttpServletRequest) request;
            HttpServletResponse httpResp = (HttpServletResponse) response;
            if (!"OPTIONS".equals(httpReq.getMethod())) {
                String authorization = httpReq.getHeader("Authorization");
                Preconditions.checkNotNull(authorization,
                        "Authorization header is required");
                String[] splitted = authorization.split(" ");
                if (!"Bearer".equals(splitted[0])) {
                    throw new AccessDeniedException("Authorization must be Bearer");
                }
                String token = splitted[1];

                Algorithm algorithm = Algorithm.HMAC256("secret");
                JWTVerifier verifier = JWT.require(algorithm)
                        .build(); //Reusable verifier instance
                DecodedJWT jwt = verifier.verify(token);
                String userId = jwt.getSubject();
                LOG.info("User: {}", userId);

                allowed = "hendy".equals(userId); // any custom logic here
            }
            if (allowed) {
                chain.doFilter(request, response);
            } else {
                httpResp.setStatus(403);
                httpResp.setHeader("Content-Type", "application/json");
                httpResp.getWriter().write(
                        "{\"error\": \"Unauthorized\", \"message\": \"Access denied\"}");
//                mapper.writeValue(httpResp.getWriter(),
//                        new Error("Unauthorized", "Access denied"));
            }
        } else {
            chain.doFilter(request, response);
        }
    }
 
Example 17
Project: EasyController   File: FileView.java   View Source Code Vote up 5 votes
/**
 * 对下载的文件名称进行编码
 */

protected String encodeFileName(HttpServletRequest request, String fileName) {
    String agent = request.getHeader("User-Agent"); // 获取浏览器
    try {
        if (agent.equalsIgnoreCase("firefox")) {
            fileName = "=?" + encoding + "?B?" + Base64.encodeToString(fileName) + "?=";
        } else {
            fileName = URLEncoder.encode(fileName, encoding);
        }
        return fileName;
    } catch (UnsupportedEncodingException e) {
        return fileName;
    }
}
 
Example 18
Project: lazycat   File: CorsFilter.java   View Source Code Vote up 4 votes
/**
 * Handles a CORS request of type {@link CORSRequestType}.SIMPLE.
 *
 * @param request
 *            The {@link HttpServletRequest} object.
 * @param response
 *            The {@link HttpServletResponse} object.
 * @param filterChain
 *            The {@link FilterChain} object.
 * @throws IOException
 * @throws ServletException
 * @see <a href="http://www.w3.org/TR/cors/#resource-requests">Simple
 *      Cross-Origin Request, Actual Request, and Redirects</a>
 */
protected void handleSimpleCORS(final HttpServletRequest request, final HttpServletResponse response,
		final FilterChain filterChain) throws IOException, ServletException {

	CorsFilter.CORSRequestType requestType = checkRequestType(request);
	if (!(requestType == CorsFilter.CORSRequestType.SIMPLE || requestType == CorsFilter.CORSRequestType.ACTUAL)) {
		throw new IllegalArgumentException(sm.getString("corsFilter.wrongType2", CorsFilter.CORSRequestType.SIMPLE,
				CorsFilter.CORSRequestType.ACTUAL));
	}

	final String origin = request.getHeader(CorsFilter.REQUEST_HEADER_ORIGIN);
	final String method = request.getMethod();

	// Section 6.1.2
	if (!isOriginAllowed(origin)) {
		handleInvalidCORS(request, response, filterChain);
		return;
	}

	if (!allowedHttpMethods.contains(method)) {
		handleInvalidCORS(request, response, filterChain);
		return;
	}

	// Section 6.1.3
	// Add a single Access-Control-Allow-Origin header.
	if (anyOriginAllowed && !supportsCredentials) {
		// If resource doesn't support credentials and if any origin is
		// allowed
		// to make CORS request, return header with '*'.
		response.addHeader(CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN, "*");
	} else {
		// If the resource supports credentials add a single
		// Access-Control-Allow-Origin header, with the value of the Origin
		// header as value.
		response.addHeader(CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN, origin);
	}

	// Section 6.1.3
	// If the resource supports credentials, add a single
	// Access-Control-Allow-Credentials header with the case-sensitive
	// string "true" as value.
	if (supportsCredentials) {
		response.addHeader(CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
	}

	// Section 6.1.4
	// If the list of exposed headers is not empty add one or more
	// Access-Control-Expose-Headers headers, with as values the header
	// field names given in the list of exposed headers.
	if ((exposedHeaders != null) && (exposedHeaders.size() > 0)) {
		String exposedHeadersString = join(exposedHeaders, ",");
		response.addHeader(CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS, exposedHeadersString);
	}

	// Forward the request down the filter chain.
	filterChain.doFilter(request, response);
}
 
Example 19
Project: MicroServiceDemo   File: JwtTokenUtil.java   View Source Code Vote up 4 votes
public String getUsername(HttpServletRequest request) {
    String token = request.getHeader(HEADER_STRING);
    return getUsername(token);
}
 
Example 20
Project: S3Mock   File: FileStoreController.java   View Source Code Vote up 4 votes
private boolean isV4SigningEnabled(final HttpServletRequest request) {
  final String sha256Header = request.getHeader(HEADER_X_AMZ_CONTENT_SHA256);
  return sha256Header != null && !sha256Header.equals(UNSIGNED_PAYLOAD);
}