Recently I've run into an issue regarding request-scoped beans. Here's the code:
@Configuration
class PreAuthorizationHttpHeaderFilterConfig {
@Bean
JwtPreAuthorizationConfigurer jwtPreAuthorizationConfigurer() {
return new JwtPreAuthorizationConfigurer();
}
@Bean
@RequestScope
TenantContext tenantContext() {
return new TenantContext();
}
}
@Getter
@Setter
public class TenantContext {
private String tenantName;
private String issuerUri;
private String jwkSetUri;
}
public class JwtPreAuthorizationConfigurer extends HttpFilter {
@Resource
private TenantContext tenantContext;
@Override
protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
tenantContext.getIssuerUri(); // <----- exception is thrown
}
}
When I access tenantContext
in my custom HttpFilter
the exception is thrown:
org.springframework.beans.factory.support.ScopeNotActiveException: Error creating bean with name 'scopedTarget.tenantContext': Scope 'request' 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 the current request.
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:383) ~[spring-beans-5.3.22.jar:5.3.22]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.22.jar:5.3.22]
at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:35) ~[spring-aop-5.3.22.jar:5.3.22]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:692) ~[spring-aop-5.3.22.jar:5.3.22]
at com.c.o.c.model.TenantContext$$EnhancerBySpringCGLIB$$4df4fdfb.setIssuerUri(<generated>) ~[classes/:na]
at com.c.o.c.filter.JwtPreAuthorizationConfigurer.doFilter(JwtPreAuthorizationConfigurer.java:30) ~[classes/:na]
But if I do the same in @RestController
-annotated class everything works fine:
@RestController
public class ConsentsController {
@Resource
private TenantContext tenantContext;
@Override
public ResponseEntity<ConsentRecord> createConsents(
@RequestBody CreateConsentRequest createConsents
) {
tenantContext.getTenantName();
return ResponseEntity.ok().body(null);
}
}
As far as I understand at the filtering step the request is already bound to a serving thread, so there shouldn't be any exception, should it?