If you are using Spring Boot, it's pretty easy to get an instance of the request and response. You can simply autowire it in via Spring:
@Autowired
private HttpServletRequest request;
@Autowired
private HttpServletResponse response;
Alternatively, pass it in the constructor or even in the controller method (which Spring will implicitly autowire).
Spring makes use of its AOP proxies so the `request` methods are always proxied to the current request.
While you can use request/response like this in any Spring DI class, I found it easier to bypass the boilerplate of constructing a context every time. What I've done is create a J2EContext and then a ProfileManager bean so I can easily autowire a context or profilemanager anywhere I want to use them. With @RequestScope, they also make use of the proxy so that particular proxied variable always refers to the current request scope even if the consumer is in a larger scope (session, singleton, etc.).
@Configuration
public class J2EContextConfig {
@Autowired
private HttpServletRequest request;
@Autowired
private HttpServletResponse response;
@Autowired
private Config config;
@Bean
@RequestScope
public J2EContext getContext() {
@SuppressWarnings("unchecked")
J2EContext context = new J2EContext(request, response, config.getSessionStore());
return context;
}
}
@Configuration
public class ProfileManagerConfig extends ProfileManagerFactoryAware<J2EContext> {
@Autowired
private J2EContext context;
@Autowired
private Config config;
@Bean
@RequestScope
public ProfileManager<CommonProfile> getProfileManager() {
@SuppressWarnings("unchecked")
ProfileManager<CommonProfile> manager = this.getProfileManager(context, config);
return manager;
}
}
Then I can get a Pac4j profile anywhere:
@Autowired
private ProfileManager<CommonProfile> profileManager;
private myMethod() {
CommonProfile profile = profileManager.get(true).orElseThrow(() -> {
return new SomeException();
});
String id = profile.getId();
// do things
}
Regards,
Bob