Java源码示例:org.apache.shiro.web.servlet.Cookie
示例1
/**
* session管理器(单机环境)
*/
@Bean
@ConditionalOnProperty(prefix = "guns", name = "spring-session-open", havingValue = "false")
public DefaultWebSessionManager defaultWebSessionManager(CacheManager cacheShiroManager, GunsProperties gunsProperties) {
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
sessionManager.setCacheManager(cacheShiroManager);
sessionManager.setSessionValidationInterval(gunsProperties.getSessionValidationInterval() * 1000);
sessionManager.setGlobalSessionTimeout(gunsProperties.getSessionInvalidateTime() * 1000);
sessionManager.setDeleteInvalidSessions(true);
sessionManager.setSessionValidationSchedulerEnabled(true);
Cookie cookie = new SimpleCookie(ShiroHttpSession.DEFAULT_SESSION_ID_NAME);
cookie.setName("shiroCookie");
cookie.setHttpOnly(true);
sessionManager.setSessionIdCookie(cookie);
return sessionManager;
}
示例2
/**
* session管理器(单机环境)
*/
@Bean
@ConditionalOnProperty(prefix = "guns", name = "spring-session-open", havingValue = "false")
public DefaultWebSessionManager defaultWebSessionManager(CacheManager cacheShiroManager, GunsProperties gunsProperties) {
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
sessionManager.setCacheManager(cacheShiroManager);
sessionManager.setSessionValidationInterval(gunsProperties.getSessionValidationInterval() * 1000);
sessionManager.setGlobalSessionTimeout(gunsProperties.getSessionInvalidateTime() * 1000);
sessionManager.setDeleteInvalidSessions(true);
sessionManager.setSessionValidationSchedulerEnabled(true);
Cookie cookie = new SimpleCookie(ShiroHttpSession.DEFAULT_SESSION_ID_NAME);
cookie.setName("shiroCookie");
cookie.setHttpOnly(true);
sessionManager.setSessionIdCookie(cookie);
return sessionManager;
}
示例3
/**
* Copy build cookie
*
* @param cookie
* @return
*/
public static IamCookie build(javax.servlet.http.Cookie cookie) {
if (isNull(cookie)) {
return null;
}
IamCookie _that = new IamCookie();
_that.setName(cookie.getName());
_that.setValue(cookie.getValue());
_that.setComment(cookie.getComment());
_that.setDomain(cookie.getDomain());
_that.setPath(cookie.getPath());
_that.setMaxAge(Math.max(DEFAULT_MAX_AGE, cookie.getMaxAge()));
_that.setVersion(Math.max(DEFAULT_VERSION, cookie.getVersion()));
_that.setSecure(cookie.getSecure());
_that.setHttpOnly(cookie.isHttpOnly());
return _that;
}
示例4
@Override
public XsrfToken getXToken(HttpServletRequest request) {
if (!isXsrfRequired(request)) {
log.debug("Requests that do not requires XSRF validation, RequestUri: %s", getRequestUri(request));
return null;
}
javax.servlet.http.Cookie cookie = getCookie(request, getXsrfTokenCookieName(request));
if (isNull(cookie)) {
return null;
}
String xtoken = cookie.getValue();
if (equalsAnyIgnoreCase(xtoken, "null", "undefined", EMPTY)) {
return null;
}
return new DefaultXsrfToken(xconfig.getXsrfHeaderName(), xconfig.getXsrfParamName(), xtoken);
}
示例5
/**
* Puts principal authorization info(roles/permissions) and common security
* headers to cookies.(if necessary)
*
* @param token
* @param request
* @param response
* @return
*/
protected Map<String, String> putAuthzInfoCookiesAndSecurityIfNecessary(AuthenticationToken token, ServletRequest request,
ServletResponse response) {
Map<String, String> authzInfo = new HashMap<>();
// Gets permits URl.
String permitUrl = getRFCBaseURI(toHttp(request), true) + URI_S_LOGIN_BASE + "/" + URI_S_LOGIN_PERMITS;
authzInfo.put(config.getParam().getAuthzPermitsName(), permitUrl);
if (isBrowser(toHttp(request))) {
// Sets authorizes permits info.
Cookie c = new IamCookie(config.getCookie());
c.setName(config.getParam().getAuthzPermitsName());
c.setValue(permitUrl);
c.setMaxAge(60);
c.saveTo(toHttp(request), toHttp(response));
// Sets common security headers.
setSecurityHeadersIfNecessary(token, request, response);
}
return authzInfo;
}
示例6
@Override
protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
// 如果参数中包含“__sid”参数,则使用此sid会话。 例如:http://localhost/project?__sid=xxx&__cookie=true
String sid = request.getParameter("__sid");
if (StringUtils.isNotBlank(sid)) {
// 是否将sid保存到cookie,浏览器模式下使用此参数。
if (WebUtils.isTrue(request, "__cookie")){
HttpServletRequest rq = (HttpServletRequest)request;
HttpServletResponse rs = (HttpServletResponse)response;
Cookie template = getSessionIdCookie();
Cookie cookie = new SimpleCookie(template);
cookie.setValue(sid); cookie.saveTo(rq, rs);
}
// 设置当前session状态
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE,
ShiroHttpServletRequest.URL_SESSION_ID_SOURCE); // session来源与url
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sid);
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
return sid;
}else{
return super.getSessionId(request, response);
}
}
示例7
@Bean
@ConditionalOnMissingBean(RememberMeManager.class)
public RememberMeManager rememberMeManager(Cookie cookie) {
CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
cookieRememberMeManager.setCookie(cookie);
cookieRememberMeManager.setCipherService(cipherService);
if (shiroCookieProperties.getCipherKey() != null) {
cookieRememberMeManager.setCipherKey(shiroCookieProperties.getCipherKey().getBytes());
} else {
if (shiroCookieProperties.getEncryptionCipherKey() != null) {
cookieRememberMeManager.setEncryptionCipherKey(shiroCookieProperties.getEncryptionCipherKey().getBytes());
}
if (shiroCookieProperties.getDecryptionCipherKey() != null) {
cookieRememberMeManager.setDecryptionCipherKey(shiroCookieProperties.getDecryptionCipherKey().getBytes());
}
}
cookieRememberMeManager.setSerializer(serializer);
return cookieRememberMeManager;
}
示例8
@Bean
@ConditionalOnMissingBean(RememberMeManager.class)
public RememberMeManager rememberMeManager(Cookie cookie) {
CookieRememberMeManager manager = new CookieRememberMeManager();
manager.setCookie(cookie);
manager.setCipherService(cipherService);
if (null != shiroCookieProperties.getCipherKey()) {
manager.setCipherKey(shiroCookieProperties.getCipherKey().getBytes());
} else {
if (null != shiroCookieProperties.getEncryptionCipherKey()) {
manager.setEncryptionCipherKey(shiroCookieProperties.getEncryptionCipherKey().getBytes());
}
if (null != shiroCookieProperties.getDecryptionCipherKey()) {
manager.setDecryptionCipherKey(shiroCookieProperties.getDecryptionCipherKey().getBytes());
}
}
manager.setSerializer(serializer);
return manager;
}
示例9
@Override
protected void rememberSerializedIdentity(Subject subject, byte[] serialized) {
if (!WebUtils.isHttp(subject)) {
if (LOGGER.isDebugEnabled()) {
String msg = "Subject argument is not an HTTP-aware instance. This is required to obtain a servlet " +
"request and response in order to set the rememberMe cookie. Returning immediately and " +
"ignoring rememberMe operation.";
LOGGER.debug(msg);
}
return;
}
HttpServletRequest request = WebUtils.getHttpRequest(subject);
HttpServletResponse response = WebUtils.getHttpResponse(subject);
// base 64 encode it and store as a cookie:
String base64 = Base64.encodeToString(serialized);
// the class attribute is really a template for the outgoing cookies
Cookie cookie = getCookie();
cookie.setValue(base64);
cookie.saveTo(request, response);
}
示例10
/**
* 构造方法
*/
public FormAuthenticationFilter() {
super();
rememberUserCodeCookie = new SimpleCookie(DEFAULT_REMEMBER_USERCODE_PARAM);
rememberUserCodeCookie.setHttpOnly(true);
rememberUserCodeCookie.setMaxAge(Cookie.ONE_YEAR);
}
示例11
@Bean
@ConditionalOnMissingBean(Cookie.class)
public Cookie rememberMeCookie() {
SimpleCookie cookie = new SimpleCookie();
cookie.setName(authFilterProperties.getRememberMeParamName());
cookie.setMaxAge(shiroCookieProperties.getMaxAge());
cookie.setValue(shiroCookieProperties.getValue());
cookie.setVersion(shiroCookieProperties.getVersion());
cookie.setHttpOnly(shiroCookieProperties.isHttpOnly());
cookie.setSecure(shiroCookieProperties.isSecure());
return cookie;
}
示例12
@Bean
public Cookie rememberMeCookie() {
SimpleCookie cookie = new SimpleCookie("rememberMe");
cookie.setHttpOnly(true);
cookie.setMaxAge(31536000);
return cookie;
}
示例13
@Inject
public void configureProperties(
@Named("${shiro.globalSessionTimeout:-" + DEFAULT_GLOBAL_SESSION_TIMEOUT + "}") final long globalSessionTimeout,
@Named("${nexus.sessionCookieName:-" + DEFAULT_NEXUS_SESSION_COOKIE_NAME + "}") final String sessionCookieName)
{
setGlobalSessionTimeout(globalSessionTimeout);
log.info("Global session timeout: {} ms", getGlobalSessionTimeout());
Cookie cookie = getSessionIdCookie();
cookie.setName(sessionCookieName);
log.info("Session-cookie prototype: name={}", cookie.getName());
}
示例14
private void storeSessionId(final Serializable currentId, final HttpServletRequest request, final HttpServletResponse response) {
if (currentId == null) {
String msg = "sessionId cannot be null when persisting for subsequent requests.";
throw new IllegalArgumentException(msg);
}
final String idString = currentId.toString();
final Cookie cookie = getSessionIdCookie();
cookie.setValue(idString);
cookie.saveTo(request, response);
LOGGER.debug("Set session ID cookie for session with id {}", idString);
}
示例15
@Override
public String readValue(HttpServletRequest request, HttpServletResponse ignored) {
String name = getName();
String value = null;
javax.servlet.http.Cookie cookie = Cookies.getCookie(request, name);
if (cookie != null) {
value = cookie.getValue();
} else {
return value;
}
return this.cookieValueManager.obtainCookieValue(getName(), value, request);
}
示例16
public IamCookie(Cookie cookie) {
super(cookie);
}
示例17
@Override
public void saveXToken(XsrfToken xtoken, HttpServletRequest request, HttpServletResponse response) {
String xtokenValue = isNull(xtoken) ? EMPTY : xtoken.getXsrfToken();
// Delete older xsrf token from cookie.
int version = -1;
Cookie oldCookie = IamCookie.build(getCookie(request, getXsrfTokenCookieName(request)));
if (!isNull(oldCookie)) {
version = oldCookie.getVersion();
oldCookie.removeFrom(request, response);
}
// New xsrf token to cookie.
Cookie cookie = new IamCookie(coreConfig.getCookie());
cookie.setName(getXsrfTokenCookieName(request));
cookie.setSecure(request.isSecure());
cookie.setValue(xtokenValue);
cookie.setVersion(++version);
if (!isBlank(xconfig.getCookiePath())) {
cookie.setPath(xconfig.getCookiePath());
} else {
// When the root path of web application access is path='/' and the
// front and back ends are separately deployed, the browser
// document.cookie can only get cookie of path='/'
cookie.setPath("/");
// cookie.setPath(getRequestContext(request));
}
if (isNull(xtoken)) {
cookie.setMaxAge(0);
} else {
cookie.setMaxAge(-1);
}
// For the implementation of xsrf token, for the front-end and back-end
// separation architecture, generally JS obtains and appends the cookie
// to the headers. At this time, httponly=true cannot be set
cookie.setHttpOnly(xconfig.isCookieHttpOnly());
// Note: due to the cross domain limitation of set cookie, it can only
// be set to the current domain or parent domain.
cookie.setDomain(getXsrfTokenCookieDomain(request));
cookie.saveTo(request, response);
}
示例18
public Cookie getRememberMeCookie() {
return rememberMeCookie;
}
示例19
public CryptCookie(final Cookie cookie) {
super(cookie);
}
示例20
/**
* Do save sessionId to cookie. </br>
*
* <p style='color:red'>
* Note: Chrome80+ Cookie default by SameSite=Lax </br>
* </br>
* You can customize the extension to fit different browser restrictions.
* </p>
*
* @param request
* @param response
* @param sessionId
*/
protected void doStorageSessionIdToCookie(HttpServletRequest request, HttpServletResponse response, Serializable sessionId) {
// Sets session cookie.
Cookie sid = new IamCookie(getSessionIdCookie());
// sid.setValue(valueOf(sessionId)+"; SameSite=None; Secure");
sid.setValue(valueOf(sessionId));
sid.saveTo(request, response);
}
示例21
/**
* 设置RememberMe Cookie的模板
* <br>如需要定制RememberMe Cookie的name、domain、httpOnly可设置此项
*
* @param rememberMeCookie see org.apache.shiro.web.servlet.SimpleCookie
*/
public ShiroCustomizer setRememberMeCookie(Cookie rememberMeCookie) {
this.rememberMeCookie = rememberMeCookie;
return self();
}