Reputation: 1606
In my Spring Boot I'd want to implement authentication via a session scoped bean.
@Service
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class AuthService {
private User user;
public boolean isLoggedIn() { return user != null; }
...
}
I defined a filter to run on every request so that I'm able to check if the user is logged or not:
@Configuration
public class AuthenticationFilter implements Filter {
@Autowired
private AuthService service;
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain ch) {
if (!service.isLoggedIn()) {
...
}
}
...
}
By the time the application calls service.isLoggedIn()
I get the exception:
org.springframework.beans.factory.support.ScopeNotActiveException: Error creating bean with name 'scopedTarget.authService': Scope 'session' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose
I suspect I'm designing this wrongly. Is there any way to make it work?
Upvotes: 0
Views: 560
Reputation: 1606
I just need to declare a bean for RequestContextListener somewhere
@Configuration
public class ContextListener {
@Bean
public RequestContextListener requestContextListener() {
return new RequestContextListener();
}
}
and then you can start using session-scoped and request-scoped beans from a singletone-scope (default) bean.
Upvotes: 1