每个请求的Spring会话创建策略?

时间:2017-04-20 15:20:00

标签: java spring spring-security

TL; DR

是否可以基于每个请求控制Spring(安全)中的会话创建策略?

长版...

我一直在为我们的应用程序使用正常的登录表单用户身份验证。 有些控制器是@RestControllers,到目前为止,cookie跟踪的默认用户会话已经允许它正常工作。

(即,当XHR请求来自页面时,请求通过以前登录的用户进行身份验证,因为浏览器会像往常一样发送JSESSIONID cookie)

我现在想允许从休息客户端而不是浏览器调用一些@RestController端点,所以我创建了一个API令牌认证方案 - 这很好。

清理的最后一点是REST调用会生成一个会话,如果可能的话我想避免。

我无法将会话策略设置为永不(因为我仍然依赖于我的网络用户的会话)。

我试过IF_REQUIRED无济于事。

我查看了HttpSessionSecurityContextRepository,但是它包装了请求,每当刷新响应时都会创建一个会话。

(参见下面的stacktrace)

是否可以在其他地方基于每个请求挂钩会话管理?

我可以根据Authentication对象的类类型轻松区分请求类型。

at myapp.cfg.WebConfig$1.sessionCreated(WebConfig.java:74)
at io.undertow.servlet.core.ApplicationListeners.sessionCreated(ApplicationListeners.java:300)
at io.undertow.servlet.core.SessionListenerBridge.sessionCreated(SessionListenerBridge.java:56)
at io.undertow.server.session.SessionListeners.sessionCreated(SessionListeners.java:52)
at io.undertow.server.session.InMemorySessionManager.createSession(InMemorySessionManager.java:187)
at io.undertow.servlet.spec.ServletContextImpl.getSession(ServletContextImpl.java:741)
at io.undertow.servlet.spec.HttpServletRequestImpl.getSession(HttpServletRequestImpl.java:370)
at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:270)
at org.springframework.security.web.context.HttpSessionSecurityContextRepository$SaveToSessionResponseWrapper.createNewSessionIfAllowed(HttpSessionSecurityContextRepository.java:427)
at org.springframework.security.web.context.HttpSessionSecurityContextRepository$SaveToSessionResponseWrapper.saveContext(HttpSessionSecurityContextRepository.java:364)
at org.springframework.security.web.context.SaveContextOnUpdateOrErrorResponseWrapper.onResponseCommitted(SaveContextOnUpdateOrErrorResponseWrapper.java:85)
at org.springframework.security.web.util.OnCommittedResponseWrapper.doOnResponseCommitted(OnCommittedResponseWrapper.java:245)
at org.springframework.security.web.util.OnCommittedResponseWrapper.access$000(OnCommittedResponseWrapper.java:33)
at org.springframework.security.web.util.OnCommittedResponseWrapper$SaveContextServletOutputStream.flush(OnCommittedResponseWrapper.java:512)
at org.springframework.security.web.util.OnCommittedResponseWrapper$SaveContextServletOutputStream.flush(OnCommittedResponseWrapper.java:513)
at com.fasterxml.jackson.core.json.UTF8JsonGenerator.flush(UTF8JsonGenerator.java:1050)
at com.fasterxml.jackson.databind.ObjectWriter.writeValue(ObjectWriter.java:953)

3 个答案:

答案 0 :(得分:2)

将安全配置拆分为单独的部分,以进行表单登录(基于会话的API访问)和无状态API令牌身份验证方案。

示例:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

    @Order(1)
    @Configuration
    class ApiSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .antMatcher("/api/**")
            .authorizeRequests().anyRequest().authenticated()
            .and()
            .httpBasic().realmName("API") // your API token authentication scheme 
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER)
            .and()
            .exceptionHandling().authenticationEntryPoint(new Http401AuthenticationEntryPoint("Form realm=\"API\"")); // prevent basic authentication popup in browser
    }
    }

    @Order(2)
    @Configuration
    class DefaultSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .formLogin().loginPage("/login").permitAll()
            .and()
            .logout().logoutSuccessUrl("/login").permitAll();
    }
    }
}

.httpBasic().realmName("API")替换为您自己的身份验证方案。

使用例如调用您的API curl -v ...并验证响应中没有Set-Cookie标头。否则,您的代码会在某处创建一个http会话。

答案 1 :(得分:0)

我遇到了完全相同的问题,找不到干净的解决方案。在没有更好的选择的情况下,我将发布一个半有用的技巧。

免责声明:我尚未使用此解决方案(至少现在暂时不参加会议),尝试此方法需要您自担风险。

覆盖默认的SecurityContextRepository

@Component
public class CustomSecurityContextRepository extends HttpSessionSecurityContextRepository {

    @Override
    public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) {
        SecurityContext securityContext = super.loadContext(requestResponseHolder);

        // disable automatic saving of security context on response committed
        // WARNING: not sure how safe this is
        SaveContextOnUpdateOrErrorResponseWrapper response = 
                (SaveContextOnUpdateOrErrorResponseWrapper)requestResponseHolder.getResponse();
        response.disableSaveOnResponseCommitted();
        return securityContext;
    }

    @Override
    public void saveContext(SecurityContext context, HttpServletRequest request,
                            HttpServletResponse response) {
        Authentication authentication = context.getAuthentication();
        // call super.saveContext according to your use case
    }
}

最后,在WebSecurityConfigurerAdapter中注册此类:

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.securityContext().securityContextRepository(customSecurityContextRepository);
}

如果有人有更好的解决方案,我将有兴趣听。

答案 2 :(得分:0)

对于API端点,您应该尝试将创建会话策略设置为“无状态”。

  

如果使用“无状态”,则表示                   应用程序保证不会创建会话。这与使用                   “永远”表示Spring Security不会创建会话,但会利用                   一个,如果应用程序这样做。

相关问题