Same-Site cookie in Spring Security

六月ゝ 毕业季﹏ 提交于 2019-12-01 04:23:17

问题


is it possible to set Same-site Cookie flag in Spring Security? See: https://tools.ietf.org/html/draft-west-first-party-cookies-07 And if not, is it on a roadmap to add support, please? There is already support in some browsers (i.e. Chrome). T.H.


回答1:


You can always set cookie values by yourself in the Java world if you can get an instance of the HttpServletResponse.

Then you can do:

response.setHeader("Set-Cookie", "key=value; HttpOnly; SameSite=strict")

In spring-security you can easily do this with a filter, here is an example:

public class CustomFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest request,  ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletResponse resp = (HttpServletResponse)response;

        resp.setHeader("Set-Cookie", "locale=de; HttpOnly; SameSite=strict");

        chain.doFilter(request, response);
    }
}

Add this filter to your SecurityConfig like this:

http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class)

Or via XML:

    <http>
        <custom-filter after="BASIC_AUTH_FILTER" ref="myFilter" />
    </http>

<beans:bean id="myFilter" class="org.bla.CustomFilter"/>



回答2:


Instead of a Filter, In your Authentication Success Handler, you can mention in this way.


    @Override
        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                Authentication authentication) throws IOException {
            response.setStatus(HttpServletResponse.SC_OK);
            clearAuthenticationAttributes(request);
            addSameSiteCookieAttribute(response);
            handle(request, response);
        }

        private void addSameSiteCookieAttribute(HttpServletResponse response) {
            Collection<String> headers = response.getHeaders(HttpHeaders.SET_COOKIE);
            boolean firstHeader = true;
            for (String header : headers) { // there can be multiple Set-Cookie attributes
                if (firstHeader) {
                    response.setHeader(HttpHeaders.SET_COOKIE, String.format("%s; %s", header, "SameSite=Strict"));
                    firstHeader = false;
                    continue;
                }
                response.addHeader(HttpHeaders.SET_COOKIE, String.format("%s; %s", header, "SameSite=Strict"));
            }
        }

It was mentioned in one of the answers. Couldn't find the link after I've implemented it.



来源:https://stackoverflow.com/questions/42998367/same-site-cookie-in-spring-security

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!