本文整理匯總了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;
}
示例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);
}
}
示例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);
}
示例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;
}
示例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;
}
示例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");
}
示例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;
}
示例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;
}
示例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();
}
示例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);
}
}
示例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;
}
示例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;
}
示例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;
}
示例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;
}