GitHub user AndrewG10i closed the discussion with a comment: How to get 
SecurityManager once Jakarta EE EnvironmentLoaderListener (@WebListener) 
triggered and Shiro environment initialized?

After coming back to this with a fresh head (and better streamlining ChatGPT 😄 
with the right questions), I finally found a clean solution.

The right place to hook in is after the Shiro environment is created by 
`@WebListener org.apache.shiro.ee.listeners.EnvironmentLoaderListener`.
Instead of trying to control listener order, the simplest approach is to wait 
until the WebEnvironment is stored in the ServletContext, and then initialize 
the VM-level singleton there.

This is mainly needed for background / timer jobs, since they’re not tied to 
any HTTP request or web context.

Code is simple and clear:
```
@WebListener
public class ShiroVMSecurityManagerBinder implements 
ServletContextAttributeListener {

    @Override
    public void attributeAdded(ServletContextAttributeEvent event) {
        bindIfShiroEnvironment(event);
    }

    @Override
    public void attributeReplaced(ServletContextAttributeEvent event) {
        bindIfShiroEnvironment(event);
    }

    private void bindIfShiroEnvironment(ServletContextAttributeEvent event) {
        if 
(!EnvironmentLoader.ENVIRONMENT_ATTRIBUTE_KEY.equals(event.getName())) {
            return;
        }

        Object value = 
event.getServletContext().getAttribute(EnvironmentLoader.ENVIRONMENT_ATTRIBUTE_KEY);
        if (value instanceof WebEnvironment env) {
            // Publish as VM-static singleton so 
SecurityUtils.getSecurityManager() works in timers/background threads
            SecurityUtils.setSecurityManager(env.getWebSecurityManager());
        }
    }
}
```

@lprimak, дякую за швидкі відповіді та чудовий проект! ;)

GitHub link: 
https://github.com/apache/shiro/discussions/2445#discussioncomment-15455639

----
This is an automatically sent email for [email protected].
To unsubscribe, please send an email to: [email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to