Reputation: 7551
I know it may not be a best design for a question like this but just for specific requirement.
Current application needs ServletContext
, HttpServletRequest
, HttpServletResponse
in to service layer for a customized authentication provider
.
Obviously without any specific configuration or inheritance following code:
@Component("myAuthenticaionProvider")
public class MyAuthenticaionProvider implements AuthenticationUserDetailsService {
@Autowired private ServletContext context;
@Autowired private HttpServletRequest request;
@Autowired private HttpServletResponse response;
.......
}
must throw exception:
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No matching bean of type [javax.servlet.http.HttpServletResponse] found for dependency:
Possible solutions I can think of:
Intercept HttpServletRequest
with a filter, but that requires an URL pattern, otherwise will intercept all URLs which I think might be a performance concern?
Create a request
scope bean in spring-security.xml or application-context.xml and then inject into current authentication provider class, to make it capable to get the HttpServletRequest
. But I think there is something wrong here, as how to initiate the request scope bean?
Then what could be the best practice?
Upvotes: 4
Views: 3216
Reputation: 3176
Have you tried to implement HttpRequestHandler interface in your authentication provider along with AuthenticationUserDetailsService?
Upvotes: 0
Reputation: 53516
Beyond being a "bad idea" a request object only lives as long as the request. You can't inject it into a singleton due to lifecycle differences. You can pass it in via a method parameter.
The closest solution matching your request is to create a ThreadLocal variable inside a catch all filter and set it there and inject that filter or a delegate to the thread local into your service. I highly suggest you avoid that.
Upvotes: 3