當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。