org.apache.shiro.web.servlet.Cookie Java Examples

The following examples show how to use org.apache.shiro.web.servlet.Cookie. 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: ShiroConfig.java    From MeetingFilm with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #2
Source File: ShiroConfig.java    From WebStack-Guns with MIT License 6 votes vote down vote up
/**
 * 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;
}
 
Example #3
Source File: IamCookie.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #4
Source File: CookieXsrfTokenRepository.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #5
Source File: CookieRememberMeManager.java    From nano-framework with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #6
Source File: AbstractIamAuthenticationFilter.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #7
Source File: SessionManager.java    From easyweb with Apache License 2.0 6 votes vote down vote up
@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);
	}
}
 
Example #8
Source File: ShiroAutoConfiguration.java    From spring-boot-shiro with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #9
Source File: ShiroAutoConfiguration.java    From utils with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #10
Source File: FormAuthenticationFilter.java    From frpMgr with MIT License 5 votes vote down vote up
/**
 * 构造方法
 */
public FormAuthenticationFilter() {
	super();
	rememberUserCodeCookie = new SimpleCookie(DEFAULT_REMEMBER_USERCODE_PARAM);
	rememberUserCodeCookie.setHttpOnly(true);
       rememberUserCodeCookie.setMaxAge(Cookie.ONE_YEAR);
}
 
Example #11
Source File: CryptCookie.java    From nano-framework with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #12
Source File: DefaultWebSessionManager.java    From nano-framework with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #13
Source File: NexusWebSessionManager.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@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());
}
 
Example #14
Source File: SecurityConfiguration.java    From java-platform with Apache License 2.0 5 votes vote down vote up
@Bean
public Cookie rememberMeCookie() {
	SimpleCookie cookie = new SimpleCookie("rememberMe");
	cookie.setHttpOnly(true);
	cookie.setMaxAge(31536000);
	return cookie;
}
 
Example #15
Source File: ShiroAutoConfiguration.java    From utils with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #16
Source File: ShiroCustomizer.java    From jsets-shiro-spring-boot-starter with Apache License 2.0 4 votes vote down vote up
public Cookie getRememberMeCookie() {
	return rememberMeCookie;
}
 
Example #17
Source File: CookieXsrfTokenRepository.java    From super-cloudops with Apache License 2.0 4 votes vote down vote up
@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);
}
 
Example #18
Source File: CryptCookie.java    From nano-framework with Apache License 2.0 4 votes vote down vote up
public CryptCookie(final Cookie cookie) {
    super(cookie);
}
 
Example #19
Source File: IamCookie.java    From super-cloudops with Apache License 2.0 4 votes vote down vote up
public IamCookie(Cookie cookie) {
	super(cookie);
}
 
Example #20
Source File: AbstractIamSessionManager.java    From super-cloudops with Apache License 2.0 3 votes vote down vote up
/**
 * 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);
}
 
Example #21
Source File: ShiroCustomizer.java    From jsets-shiro-spring-boot-starter with Apache License 2.0 2 votes vote down vote up
/**
 * 设置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();
}