A bundle for securing Dropwizard with Apache Shiro.
Add the following dependencies to pom.xml
in an existing project already using Dropwizard:
<dependency>
<groupId>org.secnod.dropwizard</groupId>
<artifactId>dropwizard-shiro</artifactId>
<version>0.2.0</version>
</dependency>
Version compatibility:
Dropwizard | Dropwizard Shiro |
---|---|
0.8.x | 0.2.0 |
0.7.x | 0.1.1 |
Add the bundle to the Dropwizard environment:
public class ApiApplication extends Application<ApiConfiguration> {
private final ShiroBundle<ApiConfiguration> shiro = new ShiroBundle<ApiConfiguration>() {
@Override
protected ShiroConfiguration narrow(ApiConfiguration configuration) {
return configuration.shiro;
}
};
@Override
public void initialize(Bootstrap<ApiConfiguration> bootstrap) {
bootstrap.addBundle(shiro);
}
}
Edit the Dropwizard YAML config file:
shiro:
iniConfigs: ["classpath:shiro.ini"]
Now create and configure shiro.ini
in the default package
on the classpath.
Shiro exceptions can be mapped to HTTP responses by adding the exception mapper for Shiro exceptions.
public class ApiApplication extends Application<ApiConfiguration> {
@Override
public void run(ApiConfiguration configuration, Environment environment) throws Exception {
environment.jersey().register(new ShiroExceptionMapper());
}
}
It is not added by default as most applications will need to customize how Shiro exceptions are mapped to HTTP responses.
The TypeFactory
for a custom user class must be added to Dropwizard:
public class ApiApplication extends Application<ApiConfiguration> {
@Override
public void run(ApiConfiguration configuration, Environment environment) throws Exception {
environment.jersey().register(new UserFactory());
}
}
See http://github.com/silb/shiro-jersey#using-shiro.
shiro:
filterUrlPattern = "/*" # The URL pattern for the Shiro servlet filter
Override ShiroBundle.createFilter(T)
.
Override ShiroBundle.createRealms(T)
.
One of my realms has a dependency to an object that is constructed in Application.run(T, Environment). How do I pass it to the realm?
Store the object in a field in the application class:
public class ApiApplication extends Application<ApiConfiguration> {
MyObject myObject;
private final ShiroBundle<ApiConfiguration> shiro = new ShiroBundle<ApiConfiguration>() {
@Override
protected Collection<Realm> createRealms(ApiConfiguration configuration) {
Realm r = new SomeRealm(myObject);
return Collections.singleton(r);
}
};
@Override
public void run(ApiConfiguration configuration, Environment environment) throws Exception {
myObject = new MyObject(configuration);
}
}
Add a SessionHandler
to Jetty:
environment.getApplicationContext().setSessionHandler(new SessionHandler());
See the supplied example application.