Java Code Examples for org.springframework.web.util.WebUtils#getCookie()

The following examples show how to use org.springframework.web.util.WebUtils#getCookie() . 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: CookieTokenProvider.java    From logsniffer with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public String getToken(final HttpServletRequest request, final HttpServletResponse response) {
	final Cookie tokenCookie = WebUtils.getCookie(request, COOKIE_KEY);
	if (tokenCookie != null && tokenCookie.getValue() != null) {
		logger.debug("Detected profile token from cookie: {}", tokenCookie.getValue());
		return tokenCookie.getValue();
	}
	final String token = UUID.randomUUID().toString();
	final CookieGenerator g = new CookieGenerator();
	g.setCookieMaxAge(Integer.MAX_VALUE);
	g.setCookiePath("/");
	g.setCookieName(COOKIE_KEY);
	g.addCookie(response, token);
	logger.debug("Generated a new token: {}", token);
	return token;
}
 
Example 2
Source File: ServletCookieValueMethodArgumentResolver.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
@Nullable
protected Object resolveName(String cookieName, MethodParameter parameter,
		NativeWebRequest webRequest) throws Exception {

	HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
	Assert.state(servletRequest != null, "No HttpServletRequest");

	Cookie cookieValue = WebUtils.getCookie(servletRequest, cookieName);
	if (Cookie.class.isAssignableFrom(parameter.getNestedParameterType())) {
		return cookieValue;
	}
	else if (cookieValue != null) {
		return this.urlPathHelper.decodeRequestString(servletRequest, cookieValue.getValue());
	}
	else {
		return null;
	}
}
 
Example 3
Source File: LocaleUtils.java    From EasyReport with Apache License 2.0 6 votes vote down vote up
/**
 * 根据当前request对象中的locale(Header的Accept属性)初始化系统国际化语言区域环境
 *
 * @param request  当前请求对象
 * @param response 当前响应对象
 */
public static void setInitLocale(final HttpServletRequest request, final HttpServletResponse response) {
    final Locale locale = request.getLocale();
    log.info("Init locale from user request,country:{},lang:{}", locale.getCountry(), locale.toLanguageTag());

    if (localeResolver instanceof CookieLocaleResolver) {
        final CookieLocaleResolver cookieLocaleResolver = (CookieLocaleResolver)localeResolver;
        final Cookie cookie = WebUtils.getCookie(request, cookieLocaleResolver.getCookieName());
        if (cookie == null) {
            setLocale(locale.toLanguageTag(), request, response);
        }
    }
    if (localeResolver instanceof SessionLocaleResolver) {
        final Locale sessionLocale = (Locale)WebUtils.getRequiredSessionAttribute(
            request, SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME);
        if (sessionLocale == null) {
            setLocale(locale.toLanguageTag(), request, response);
        }
    }
}
 
Example 4
Source File: LogonImpl.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public String getCookieHostId() {
    Cookie cookie = WebUtils.getCookie(request, hostIdCookieName);

    if (cookie == null) {
        if (logger.isInfoEnabled()) {
            logger.info("No host ID cookie found for host " + request.getRemoteHost() + " (" + request.getRemoteAddr() + ")");
        }

        return null;
    }

    if (logger.isInfoEnabled()) {
        logger.info("Found host ID '" + cookie.getValue() + "' found for host " + request.getRemoteHost() + " (" + request.getRemoteAddr() + ")");
    }

    return cookie.getValue();
}
 
Example 5
Source File: CookieThemeResolver.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public String resolveThemeName(HttpServletRequest request) {
	// Check request for preparsed or preset theme.
	String themeName = (String) request.getAttribute(THEME_REQUEST_ATTRIBUTE_NAME);
	if (themeName != null) {
		return themeName;
	}

	// Retrieve cookie value from request.
	Cookie cookie = WebUtils.getCookie(request, getCookieName());
	if (cookie != null) {
		String value = cookie.getValue();
		if (StringUtils.hasText(value)) {
			themeName = value;
		}
	}

	// Fall back to default theme.
	if (themeName == null) {
		themeName = getDefaultThemeName();
	}
	request.setAttribute(THEME_REQUEST_ATTRIBUTE_NAME, themeName);
	return themeName;
}
 
Example 6
Source File: TokenAuthenticationHelper.java    From spring-security-jwt-csrf with MIT License 6 votes vote down vote up
static Authentication getAuthentication(HttpServletRequest request) {

        Cookie cookie = WebUtils.getCookie(request, COOKIE_BEARER);
        String token = cookie != null ? cookie.getValue() : null;

        if (token != null) {
            Claims claims = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();

            Collection<? extends GrantedAuthority> authorities =
                    Arrays.stream(claims.get("authorities").toString().split(","))
                            .map(SimpleGrantedAuthority::new)
                            .collect(Collectors.toList());

            String userName = claims.getSubject();
            return userName != null ? new UsernamePasswordAuthenticationToken(userName, null, authorities) : null;
        }
        return null;
    }
 
Example 7
Source File: ServletCookieValueMethodArgumentResolver.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
@Nullable
protected Object resolveName(String cookieName, MethodParameter parameter,
		NativeWebRequest webRequest) throws Exception {

	HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
	Assert.state(servletRequest != null, "No HttpServletRequest");

	Cookie cookieValue = WebUtils.getCookie(servletRequest, cookieName);
	if (Cookie.class.isAssignableFrom(parameter.getNestedParameterType())) {
		return cookieValue;
	}
	else if (cookieValue != null) {
		return this.urlPathHelper.decodeRequestString(servletRequest, cookieValue.getValue());
	}
	else {
		return null;
	}
}
 
Example 8
Source File: AngularCookieLocaleResolver.java    From ServiceCutter with Apache License 2.0 5 votes vote down vote up
private void parseLocaleCookieIfNecessary(HttpServletRequest request) {
    if (request.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME) == null) {
        // Retrieve and parse cookie value.
        Cookie cookie = WebUtils.getCookie(request, getCookieName());
        Locale locale = null;
        TimeZone timeZone = null;
        if (cookie != null) {
            String value = cookie.getValue();

            // Remove the double quote
            value = StringUtils.replace(value, "%22", "");

            String localePart = value;
            String timeZonePart = null;
            int spaceIndex = localePart.indexOf(' ');
            if (spaceIndex != -1) {
                localePart = value.substring(0, spaceIndex);
                timeZonePart = value.substring(spaceIndex + 1);
            }
            locale = (!"-".equals(localePart) ? StringUtils.parseLocaleString(localePart.replace('-', '_')) : null);
            if (timeZonePart != null) {
                timeZone = StringUtils.parseTimeZoneString(timeZonePart);
            }
            if (logger.isTraceEnabled()) {
                logger.trace("Parsed cookie value [" + cookie.getValue() + "] into locale '" + locale +
                        "'" + (timeZone != null ? " and time zone '" + timeZone.getID() + "'" : ""));
            }
        }
        request.setAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME,
                (locale != null ? locale: determineDefaultLocale(request)));

        request.setAttribute(TIME_ZONE_REQUEST_ATTRIBUTE_NAME,
                (timeZone != null ? timeZone : determineDefaultTimeZone(request)));
    }
}
 
Example 9
Source File: ServletCookieValueMethodArgumentResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected Object resolveName(String cookieName, MethodParameter parameter, NativeWebRequest webRequest) throws Exception {
	HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
	Cookie cookieValue = WebUtils.getCookie(servletRequest, cookieName);
	if (Cookie.class.isAssignableFrom(parameter.getNestedParameterType())) {
		return cookieValue;
	}
	else if (cookieValue != null) {
		return this.urlPathHelper.decodeRequestString(servletRequest, cookieValue.getValue());
	}
	else {
		return null;
	}
}
 
Example 10
Source File: AngularCookieLocaleResolver.java    From expper with GNU General Public License v3.0 5 votes vote down vote up
private void parseLocaleCookieIfNecessary(HttpServletRequest request) {
    if (request.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME) == null) {
        // Retrieve and parse cookie value.
        Cookie cookie = WebUtils.getCookie(request, getCookieName());
        Locale locale = null;
        TimeZone timeZone = null;
        if (cookie != null) {
            String value = cookie.getValue();

            // Remove the double quote
            value = StringUtils.replace(value, "%22", "");

            String localePart = value;
            String timeZonePart = null;
            int spaceIndex = localePart.indexOf(' ');
            if (spaceIndex != -1) {
                localePart = value.substring(0, spaceIndex);
                timeZonePart = value.substring(spaceIndex + 1);
            }
            locale = (!"-".equals(localePart) ? StringUtils.parseLocaleString(localePart.replace('-', '_')) : null);
            if (timeZonePart != null) {
                timeZone = StringUtils.parseTimeZoneString(timeZonePart);
            }
            if (logger.isTraceEnabled()) {
                logger.trace("Parsed cookie value [" + cookie.getValue() + "] into locale '" + locale +
                    "'" + (timeZone != null ? " and time zone '" + timeZone.getID() + "'" : ""));
            }
        }
        request.setAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME,
            (locale != null ? locale: determineDefaultLocale(request)));

        request.setAttribute(TIME_ZONE_REQUEST_ATTRIBUTE_NAME,
            (timeZone != null ? timeZone : determineDefaultTimeZone(request)));
    }
}
 
Example 11
Source File: CookieCsrfTokenRepository.java    From xmanager with Apache License 2.0 5 votes vote down vote up
@Override
public CsrfTokenBean loadToken(HttpServletRequest request) {
	Cookie cookie = WebUtils.getCookie(request, this.cookieName);
	if (cookie == null) {
		return null;
	}
	String token = cookie.getValue();
	if (!StringUtils.hasLength(token)) {
		return null;
	}
	return new CsrfTokenBean(this.headerName, this.parameterName, token);
}
 
Example 12
Source File: CookieThemeResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public String resolveThemeName(HttpServletRequest request) {
	// Check request for preparsed or preset theme.
	String themeName = (String) request.getAttribute(THEME_REQUEST_ATTRIBUTE_NAME);
	if (themeName != null) {
		return themeName;
	}

	// Retrieve cookie value from request.
	String cookieName = getCookieName();
	if (cookieName != null) {
		Cookie cookie = WebUtils.getCookie(request, cookieName);
		if (cookie != null) {
			String value = cookie.getValue();
			if (StringUtils.hasText(value)) {
				themeName = value;
			}
		}
	}

	// Fall back to default theme.
	if (themeName == null) {
		themeName = getDefaultThemeName();
	}
	request.setAttribute(THEME_REQUEST_ATTRIBUTE_NAME, themeName);
	return themeName;
}
 
Example 13
Source File: AngularCookieLocaleResolver.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 5 votes vote down vote up
private void parseLocaleCookieIfNecessary(HttpServletRequest request) {
    if (request.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME) == null) {
        // Retrieve and parse cookie value.
        Cookie cookie = WebUtils.getCookie(request, getCookieName());
        Locale locale = null;
        TimeZone timeZone = null;
        if (cookie != null) {
            String value = cookie.getValue();

            // Remove the double quote
            value = StringUtils.replace(value, "%22", "");

            String localePart = value;
            String timeZonePart = null;
            int spaceIndex = localePart.indexOf(' ');
            if (spaceIndex != -1) {
                localePart = value.substring(0, spaceIndex);
                timeZonePart = value.substring(spaceIndex + 1);
            }
            locale = (!"-".equals(localePart) ? StringUtils.parseLocaleString(localePart.replace('-', '_')) : null);
            if (timeZonePart != null) {
                timeZone = StringUtils.parseTimeZoneString(timeZonePart);
            }
            if (logger.isTraceEnabled()) {
                logger.trace("Parsed cookie value [" + cookie.getValue() + "] into locale '" + locale +
                    "'" + (timeZone != null ? " and time zone '" + timeZone.getID() + "'" : ""));
            }
        }
        request.setAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME,
            (locale != null ? locale: determineDefaultLocale(request)));

        request.setAttribute(TIME_ZONE_REQUEST_ATTRIBUTE_NAME,
            (timeZone != null ? timeZone : determineDefaultTimeZone(request)));
    }
}
 
Example 14
Source File: CookieThemeResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public String resolveThemeName(HttpServletRequest request) {
	// Check request for preparsed or preset theme.
	String themeName = (String) request.getAttribute(THEME_REQUEST_ATTRIBUTE_NAME);
	if (themeName != null) {
		return themeName;
	}

	// Retrieve cookie value from request.
	String cookieName = getCookieName();
	if (cookieName != null) {
		Cookie cookie = WebUtils.getCookie(request, cookieName);
		if (cookie != null) {
			String value = cookie.getValue();
			if (StringUtils.hasText(value)) {
				themeName = value;
			}
		}
	}

	// Fall back to default theme.
	if (themeName == null) {
		themeName = getDefaultThemeName();
	}
	request.setAttribute(THEME_REQUEST_ATTRIBUTE_NAME, themeName);
	return themeName;
}
 
Example 15
Source File: TokenAuthenticationHelper.java    From SpringSecurity-JWT-Vue-Deom with MIT License 5 votes vote down vote up
/**
 * 对请求的验证
 * */
public static Authentication getAuthentication(HttpServletRequest request) {

    Cookie cookie = WebUtils.getCookie(request, COOKIE_TOKEN);
    String token = cookie != null ? cookie.getValue() : null;

    if (token != null) {
        Claims claims = Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();

        // 获取用户权限
        Collection<? extends GrantedAuthority> authorities =
                Arrays.stream(claims.get("authorities").toString().split(","))
                        .map(SimpleGrantedAuthority::new)
                        .collect(Collectors.toList());

        String userName = claims.getSubject();
        if (userName != null) {
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userName, null, authorities);
            usernamePasswordAuthenticationToken.setDetails(claims);
            return usernamePasswordAuthenticationToken;
        }
        return null;
    }
    return null;
}
 
Example 16
Source File: XISControllerService.java    From XS2A-Sandbox with Apache License 2.0 5 votes vote down vote up
public ResponseEntity<SCALoginResponseTO> performLoginForConsent(String login, String pin, String operationId, String authId, OpTypeTO operationType) {
    Cookie cookie = WebUtils.getCookie(request, ACCESS_TOKEN_COOKIE);
    String token = cookie != null
                       ? cookie.getValue()
                       : null;
    return performLoginForConsent(login, pin, token, operationId, authId, operationType);
}
 
Example 17
Source File: CookieUtil.java    From hello-sso-jwt-auth with MIT License 4 votes vote down vote up
public static String getValue(HttpServletRequest httpServletRequest, String name) {
    Cookie cookie = WebUtils.getCookie(httpServletRequest, name);
    return cookie != null ? cookie.getValue() : null;
}
 
Example 18
Source File: CookieLocaleResolver.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private void parseLocaleCookieIfNecessary(HttpServletRequest request) {
	if (request.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME) == null) {
		// Retrieve and parse cookie value.
		Cookie cookie = WebUtils.getCookie(request, getCookieName());
		Locale locale = null;
		TimeZone timeZone = null;
		if (cookie != null) {
			String value = cookie.getValue();
			String localePart = value;
			String timeZonePart = null;
			int spaceIndex = localePart.indexOf(' ');
			if (spaceIndex != -1) {
				localePart = value.substring(0, spaceIndex);
				timeZonePart = value.substring(spaceIndex + 1);
			}
			try {
				locale = (!"-".equals(localePart) ? parseLocaleValue(localePart) : null);
				if (timeZonePart != null) {
					timeZone = StringUtils.parseTimeZoneString(timeZonePart);
				}
			}
			catch (IllegalArgumentException ex) {
				if (request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) != null) {
					// Error dispatch: ignore locale/timezone parse exceptions
					if (logger.isDebugEnabled()) {
						logger.debug("Ignoring invalid locale cookie '" + getCookieName() +
								"' with value [" + value + "] due to error dispatch: " + ex.getMessage());
					}
				}
				else {
					throw new IllegalStateException("Invalid locale cookie '" + getCookieName() +
							"' with value [" + value + "]: " + ex.getMessage());
				}
			}
			if (logger.isDebugEnabled()) {
				logger.debug("Parsed cookie value [" + cookie.getValue() + "] into locale '" + locale +
						"'" + (timeZone != null ? " and time zone '" + timeZone.getID() + "'" : ""));
			}
		}
		request.setAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME,
				(locale != null ? locale : determineDefaultLocale(request)));
		request.setAttribute(TIME_ZONE_REQUEST_ATTRIBUTE_NAME,
				(timeZone != null ? timeZone : determineDefaultTimeZone(request)));
	}
}
 
Example 19
Source File: CookieUtil.java    From hellokoding-courses with MIT License 4 votes vote down vote up
public static String getValue(HttpServletRequest httpServletRequest, String name) {
    Cookie cookie = WebUtils.getCookie(httpServletRequest, name);
    return cookie != null ? cookie.getValue() : null;
}
 
Example 20
Source File: CookieUtil.java    From hello-sso-jwt-resource with MIT License 4 votes vote down vote up
public static String getValue(HttpServletRequest httpServletRequest, String name) {
    Cookie cookie = WebUtils.getCookie(httpServletRequest, name);
    return cookie != null ? cookie.getValue() : null;
}