Introduction
This blog will discuss how we can implement user authentication in dropwizard in various methods. Multiple classes or methods are available in dropwizard to implement the authentication for a user. Before we discuss dropwizard authentication, let's have a brief about dropwizard in general.

Dropwizard is a java based web framework that is used to create high-performance RESTFUL web services and is open source.
Authentication in Dropwizard

There are two types of authentication provided by the dropwizard-auth client.
- HTTP Basic authentication
- OAuth2 Bearer token
Authenticators
An authenticator is a class available in dropwizard authentication whose role is to return a principle when provided with client credentials. To use the authenticator implement the Authenticator<C, P extends Principal> interface with only one method.
Example.
The following authenticator program will use the basic auth credentials. In the program, our password client-provided password will be codingninjas, and if it matches with the user input, then the client will be recognized as a user; otherwise, optional will be returned as empty, indicating the user is invalid.
public class Authenticatorsample implements Authenticator<BasicCredentials, User> {
@Override
public Optional<User> authenticate(BasicCredentials usercredentials) throws AuthenticationException {
if ("codingninjas".equals(usercredentials.getPassword())) {
return Optional.of(new User(usercredentials.getUsername()));
}
return Optional.empty();
}
}Caching
Dropwizard authentication has a decorator class that offers caching because the supporting data stores for authenticators (an RDBMS or LDAP server, for example) might not be able to manage high throughput:
SimpleAuthenticator simpleAuthenticator = new SimpleAuthenticator();
CachingAuthenticator<BasicCredentials, User> cachingAuthenticator = new CachingAuthenticator<>(
metricRegistry, simpleAuthenticator,
config.getAuthenticationCachePolicy());Authorizer
An authorizer is a class available in dropwizard authentication that we can use to decide whether to grant access to the principal depending on the role and principal of the client. To use the authorizer implement the Authorizer<P extends Principal> interface with only one method.
Example.
public class AuthorizerSample implements Authorizer<User> {
@Override
public boolean authorize(User userdata, String role) {
return user.getName().equals("ninja-guy") && role.equals("Admin");
}
}Above, we will return true or false depending on the userdata matches with provided name and role, which are ninja-guy and ADMIN.
Basic Authentication
Now, we will learn how to implement HTTP-based authentication with the help of AuthDynamicFeature with the BasicCredentialAuthFilter and RolesAllowedDynamicFeature
Example.
@Override
public void run(ExampleConfiguration configuration,
Environment environment) {
environment.jersey().register(new AuthDynamicFeature(
new BasicCredentialAuthFilter.Builder<User>()
.setAuthenticator(new AuthenticatorSample())
.setAuthorizer(new AuthorizerSample())
.setRealm("CONFIDENTIAL INFORMATION")
.buildAuthFilter()));
environment.jersey().register(RolesAllowedDynamicFeature.class);
environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));
}RolesAllowedDynamicFeature is not necessary if authorization is not used.
OAuth2 Bearer
In this section, we will implement OAuth2 Bearer Token with the help of AuthDynamicFeature with the OAuthCredentialAuthFilter and RolesAllowedDynamicFeature.
Example.
@Override
public void run(ExampleConfiguration configuration,
Environment environment) {
environment.jersey().register(new AuthDynamicFeature(
new OAuthCredentialAuthFilter.Builder<User>()
.setAuthenticator(new OAuthAuthenticatorSample())
.setAuthorizer(new AuthorizerSample())
.setPrefix("Bearer")
.buildAuthFilter()));
environment.jersey().register(RolesAllowedDynamicFeature.class);
environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));
}RolesAllowedDynamicFeature is not necessary if authorization is not used.
Chained factories
With the help of Chained AuthFilter, you can implement various authentication factories at the same time in a program.
Example.
@Override
public void run(ExampleConfiguration configuration,
Environment environment) {
AuthFilter basicCredential = new BasicCredentialAuthFilter.Builder<>()
.setAuthenticator(new BasicAuthenticatorSample())
.setAuthorizer(new AuthorizerSample())
.setPrefix("HTTP BASIC")
.buildAuthFilter();
AuthFilter oauthCredential = new OAuthCredentialAuthFilter.Builder<>()
.setAuthenticator(new OAuthAuthenticatorSample())
.setAuthorizer(new AuthorizerSample())
.setPrefix("BEARER")
.buildAuthFilter();
List<AuthFilter> filters = Lists.newArrayList(basicCredential, oauthCredential);
environment.jersey().register(new AuthDynamicFeature(new ChainedAuthFilter(filters)));
environment.jersey().register(RolesAllowedDynamicFeature.class);
environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));
}Protection Resources
Protecting a resource is also one of the features available in dropwizard authentication. There are mainly two ways of protecting resources.
To mark it protected, you can label the resource method with the following annotations.
- @PermitAll: All users will be permitted to use this resource.
- @RolesAllowed: Users with the designated roles will be given access.
- @DenyAll: No access.
By including a parameter in your method's @Context SecurityContext context, you can also gain access to the Principal. One of @PermitAll, @RolesAllowed, or @DenyAll will still need to be included. With @Auth, this is not the case. When that occurs, the auth filter is automatically registered to make it easier for users to upgrade from earlier Dropwizard versions.
Example.
@RolesAllowed("ADMIN")
@GET
public Secrettext getSecrettext(@Context SecurityContext context) {
User principalOfUser = (User) context.getUserPrincipal();
return dao.findPlanForUser(principalOfUser);
}Testing Protected Resources
To test the protected resources, you need the following dependencies in the pom.xml file.
<dependencies>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-testing</artifactId>
<version>${dropwizard.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-grizzly2</artifactId>
<version>${jersey.version}</version>
<exclusions>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</exclusion>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
After adding the above dependency, you need to add the GrizzlyWebTestContainerFactory when building your ResourceExtension.
For Example,
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())Multiple Authenticators
In dropwizard authentication, you can apply different authentication methods for different resources. For example, you may need to use the BasicAuthentication and OAuth methods for different schemes depending on the resource. You can implement this by using some annotations available in dropwizard authentication.
Follow these steps to implement the multiple authenticators.
- A map that associates principal types with authentication filters should be registered with the PolymorphicAuthDynamicFeature.
- You should register the PolymorphicAuthValueFactoryProvider with the primary classes you intend to use.
-
Put @Auth in front of the Principal parameters in your resource method.
You can also check about Java Tokens here.




