当前位置: 首页>>代码示例>>Java>>正文


Java HttpServletRequest.getHeader方法代码示例

本文整理汇总了Java中javax.servlet.http.HttpServletRequest.getHeader方法的典型用法代码示例。如果您正苦于以下问题:Java HttpServletRequest.getHeader方法的具体用法?Java HttpServletRequest.getHeader怎么用?Java HttpServletRequest.getHeader使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在javax.servlet.http.HttpServletRequest的用法示例。


在下文中一共展示了HttpServletRequest.getHeader方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getAuthentication

import javax.servlet.http.HttpServletRequest; //导入方法依赖的package包/类
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;
}
 
开发者ID:Clcanny,项目名称:MicroServiceDemo,代码行数:18,代码来源:JwtTokenUtil.java

示例2: doFilter

import javax.servlet.http.HttpServletRequest; //导入方法依赖的package包/类
@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);
	}
}
 
开发者ID:PacktPublishing,项目名称:Practical-Microservices,代码行数:37,代码来源:JwtAuthenticationTokenFilter.java

示例3: doFilter

import javax.servlet.http.HttpServletRequest; //导入方法依赖的package包/类
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);
}
 
开发者ID:AwesomeTickets,项目名称:ServiceServer,代码行数:15,代码来源:CORSFilter.java

示例4: preHandle

import javax.servlet.http.HttpServletRequest; //导入方法依赖的package包/类
@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;
}
 
开发者ID:shout-star,项目名称:uroborosql-springboot-demo,代码行数:27,代码来源:AuthInterceptor.java

示例5: preHandle

import javax.servlet.http.HttpServletRequest; //导入方法依赖的package包/类
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;
}
 
开发者ID:CodeDogDream,项目名称:CampusHelp,代码行数:25,代码来源:MyInterceptor.java

示例6: getUsetAgent

import javax.servlet.http.HttpServletRequest; //导入方法依赖的package包/类
private static String getUsetAgent() {
	HttpServletRequest request = getCurrentRequest();
	if (request == null) {
		return null;
	}
	return request.getHeader("user-agent");
}
 
开发者ID:szsucok,项目名称:sucok-framework,代码行数:8,代码来源:WebUtils.java

示例7: preHandle

import javax.servlet.http.HttpServletRequest; //导入方法依赖的package包/类
@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;
}
 
开发者ID:guolf,项目名称:pds,代码行数:38,代码来源:AuthorizationInterceptor.java

示例8: extractTraceIdFromRequest

import javax.servlet.http.HttpServletRequest; //导入方法依赖的package包/类
@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;
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-gcp,代码行数:13,代码来源:XCloudTraceIdExtractor.java

示例9: refreshAndGetAuthenticationToken

import javax.servlet.http.HttpServletRequest; //导入方法依赖的package包/类
@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);
    }
}
 
开发者ID:rfreedman,项目名称:tour-of-heros-api-security-zerhusen,代码行数:14,代码来源:AuthenticationRestController.java

示例10: getUserAgent

import javax.servlet.http.HttpServletRequest; //导入方法依赖的package包/类
private Optional<String> getUserAgent(HttpServletRequest request) {
    String userAgentHeaderString = request.getHeader("User-Agent");
    if (null != userAgentHeaderString) {
        return Optional.of(userAgentHeaderString);
    }
    return Optional.empty();
}
 
开发者ID:aws,项目名称:aws-xray-sdk-java,代码行数:8,代码来源:AWSXRayServletFilter.java

示例11: doFilter

import javax.servlet.http.HttpServletRequest; //导入方法依赖的package包/类
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);
	}

}
 
开发者ID:guokezheng,项目名称:automat,代码行数:29,代码来源:CsrfFilter.java

示例12: getIP

import javax.servlet.http.HttpServletRequest; //导入方法依赖的package包/类
/**
 * 获取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;
}
 
开发者ID:crossoverJie,项目名称:SSM-DUBBO-HTTP,代码行数:37,代码来源:DubboController.java

示例13: getServerBaseUrl

import javax.servlet.http.HttpServletRequest; //导入方法依赖的package包/类
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;
}
 
开发者ID:bingo-oss,项目名称:sso-client,代码行数:16,代码来源:Urls.java

示例14: getHeadersInfo

import javax.servlet.http.HttpServletRequest; //导入方法依赖的package包/类
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;
}
 
开发者ID:asmodeirus,项目名称:BackOffice,代码行数:13,代码来源:PlantainController.java

示例15: getUserState

import javax.servlet.http.HttpServletRequest; //导入方法依赖的package包/类
@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;
}
 
开发者ID:equella,项目名称:Equella,代码行数:32,代码来源:OAuthUserStateHook.java


注:本文中的javax.servlet.http.HttpServletRequest.getHeader方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。