IT story

web.xml에서 HttpSession을 끌 수 있습니까?

hot-time 2021. 1. 7. 20:01
반응형

web.xml에서 HttpSession을 끌 수 있습니까?


HttpSession을 완전히 제거하고 싶습니다. web.xml에서이 작업을 수행 할 수 있습니까? 나는 그것을 할 수있는 컨테이너 특정 방법이 있다고 확신합니다 (Google 검색을 할 때 검색 결과를 복잡하게 만드는 것입니다).

추신 이것은 나쁜 생각입니까? 실제로 필요할 때까지 완전히 비활성화하는 것을 선호합니다.


HttpSession을 완전히 제거하고 싶습니다.

완전히 비활성화 할 수는 없습니다. 당신이해야 할 모든 단지입니다 하지 에 의해 하나 그것의 핸들을 얻기 위해 request.getSession()또는 request.getSession(true)어디서든 웹 어플리케이션의 코드에 있는지 JSP를 암시 적으로 설정하여 해당하지 않는 만들기 <%@page session="false"%>.

주요 관심사가 실제로에서 사용 된 쿠키를 비활성화하는 HttpSession것이라면 Java EE 5 / Servlet 2.5에서는 서버 별 웹 애플리케이션 구성에서만 그렇게 할 수 있습니다. 예를 들어, 당신은 설정할 수 있습니다 바람둥이 cookies에 속성 false<Context>요소입니다.

<Context cookies="false">

또한이 Tomcat 관련 문서를 참조하십시오 . 이런 식으로 세션은 URL 재 작성되지 않은 후속 요청에서 유지되지 않습니다. 결국, 당신이 필요하지 않은 경우, 단지 모두에서 유지 /가 작성되지 않습니다 다음, 그것을 잡아하지 않습니다.

또는 이미 Java EE 6 / Servlet 3.0 이상을 사용 중이고을 통해 실제로 수행하려는 web.xml경우 다음 과 같이 <cookie-config>요소를 사용 web.xml하여 최대 연령을 제로 아웃 할 수 있습니다 .

<session-config>
    <session-timeout>1</session-timeout>
    <cookie-config>
        <max-age>0</max-age>
    </cookie-config>
</session-config>

그 때문에 당신이 당신의 웹 어플리케이션에 하드 코드 원하는 경우 getSession()다시 발생하지 HttpSession(또는이 "비어" HttpSession), 당신은에 필터 청취을 만들어야 url-pattern/*하는 것은 대체 HttpServletRequestHttpServletRequestWrapper구현하는 모든 수익률 getSession()방법 null, 또는 더미 사용자 정의 HttpSession아무것도하지 않거나 UnsupportedOperationException.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    chain.doFilter(new HttpServletRequestWrapper((HttpServletRequest) request) {
        @Override
        public HttpSession getSession() {
            return null;
        }
        @Override
        public HttpSession getSession(boolean create) {
            return null;
        }
    }, response);
}

추신 이것은 나쁜 생각입니까? 실제로 필요할 때까지 완전히 비활성화하는 것을 선호합니다.

필요하지 않으면 사용하지 마십시오. 그게 다야. 정말 :)


상태 비 저장 고부하 애플리케이션을 빌드하는 경우 다음과 같이 세션 추적을 위해 쿠키 사용을 비활성화 할 수 있습니다 (비침 입적, 아마도 컨테이너에 구애받지 않음).

<session-config>
    <tracking-mode>URL</tracking-mode>
</session-config>

이 아키텍처 결정을 적용하려면 다음과 같이 작성하십시오.

public class PreventSessionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent se) {
    throw new IllegalStateException("Session use is forbidden");
}

@Override
public void sessionDestroyed(HttpSessionEvent se) {
    throw new IllegalStateException("Session use is forbidden");
}
}

그리고 그것을 web.xml에 추가하고 예외로 실패한 곳을 수정하십시오.

<listener>
    <listener-class>com.ideas.bucketlist.web.PreventSessionListener</listener-class>
</listener>

RESTful 앱에 대해 다음 방법을 사용하여 의도하지 않은 세션 쿠키가 생성 되고 사용 되지 않도록 제거합니다 .

<session-config>
    <session-timeout>1</session-timeout>
    <cookie-config>
        <max-age>0</max-age>
    </cookie-config>
</session-config>

그러나 이것은 HttpSession을 완전히 끄지 않습니다. 세션이 1 분 안에 사라지고 악성 클라이언트가 쿠키에 대한 max-age 요청을 무시하더라도 응용 프로그램에서 부주의하게 세션을 생성 할 수 있습니다.

The advantage of this approach is you don't need to change your application, just web.xml. I would recommend you create an HttpSessionListener that will log when a session is created or destroyed so you can track when it occurs.


In Spring Security 3 with Java Config, you can use HttpSecurity.sessionManagement():

@Override
protected void configure(final HttpSecurity http) throws Exception {
    http
        .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

Xml looks like this;

<http create-session="stateless">
  <!-- config -->
</http>

By the way, the difference between NEVER and STATELESS

NEVER:Spring Security will never create an HttpSession, but will use the HttpSession if it already exists

STATELESS:Spring Security will never create an HttpSession and it will never use it to obtain the SecurityContext


Rather than disabling you can rewrite the URL using a URL rewrite filter eg tuckey rewrite filter. This will give Google friendly results but still allow cookie based session handling.

However, you should probably disable it for all responses as it's worse than just search engine unfriendly. It exposes the session ID which can be used for certain security exploits.

Example config for Tuckey filter:

<outbound-rule encodefirst="true">
  <name>Strip URL Session ID's</name>
  <from>^(.*?)(?:\;jsessionid=[^\?#]*)?(\?[^#]*)?(#.*)?$</from>
  <to>$1$2$3</to>
</outbound-rule>

I would like to eliminate the HttpSession completely - can I do this in web.xml? I'm sure there are container specific ways to do it

I don't think so. Disabling the HttpSession would be a violation of the Servlet spec which states that HttpServletRequest#getSession should return a session or create one. So I wouldn't expect a Java EE container to provide such a configuration option (that would make it non compliant).

Is this a bad idea? I prefer to completely disable things until I actually need them.

Well, I don't really get the point, just don't put anything in the session if you don't want to use it. Now, if you really want to prevent the use of the session, you can use a Filter to replace the request with a implementation of HttpServletRequestWrapper overriding getSession(). But I wouldn't waste time implementing this :)

Update: My initial suggestion was not optimal, the "right" (cough) way would be to replace the request.


As of Servlet 3.0, you can make it so sessions are not tracked by the servlet container in any way, by adding code like this to the contextInitialized method of a ServletContextListener:

servletContext.setSessionTrackingModes(Collections.emptySet());

Javadoc.


For RESTful application, I simply invalidate it every time the request's lifecycle ends. There may be some web server that always creates new session when new client access whether you call request.getSession() or not.


One cannot avoid the session creation. But you can check if you violate your own requirement at the end of a request cycle. So, create a simple servlet filter, which you place as first and after chain.doFilter throw an exception if a session was created:

chain.doFilter(request, response);
if(request.getSession(false) != null)
    throw new RuntimeException("Somewhere request.getSession() was called");

ReferenceURL : https://stackoverflow.com/questions/2255814/can-i-turn-off-the-httpsession-in-web-xml

반응형