Table of contents
1.
Introduction
2.
Authentication in Dropwizard
2.1.
Authenticators
2.1.1.
Caching
2.2.
Authorizer
2.3.
Basic Authentication
2.4.
OAuth2 Bearer 
2.5.
Chained factories
2.6.
Protection Resources
2.7.
Testing Protected Resources
2.8.
Multiple Authenticators
3.
Frequently Asked Questions
3.1.
How many methods are available in dropwizard authentication?
3.2.
Can we implement more than one authentication method in a project?
3.3.
Can we add access permissions to a particular resource in dropwizard authentication?
3.4.
What is the difference between Authenticator and Authorizer classes?
3.5.
Where to use @RolesAllowed and  @PermitAll annotations?
4.
Conclusion
Last Updated: Mar 27, 2024
Medium

Dropwizard Authentication

Author dhananjay
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

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 logo

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

Authentication in Dropwizard

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();
    }
}
You can also try this code with Online Java Compiler
Run Code

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());
You can also try this code with Online Java Compiler
Run Code

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");
    }
}
You can also try this code with Online Java Compiler
Run Code

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));
}
You can also try this code with Online Java Compiler
Run Code

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));
}
You can also try this code with Online Java Compiler
Run Code

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));
}
You can also try this code with Online Java Compiler
Run Code

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);
}
You can also try this code with Online Java Compiler
Run Code

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())
You can also try this code with Online Java Compiler
Run Code

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.

Frequently Asked Questions

How many methods are available in dropwizard authentication?

There are two types of authentication methods on dropwizard, HTTP  Basic authentication, and OAuth2 Bearer token.

Can we implement more than one authentication method in a project?

Yes, we can implement both authentication methods in one program.

Can we add access permissions to a particular resource in dropwizard authentication?

Yes, by using annotation @RolesAllowed we can provide access to a particular user.

What is the difference between Authenticator and Authorizer classes?

The authenticator class provides the principal verify user credentials and the Authorizer class provides access depending on the user role and principal.

Where to use @RolesAllowed and  @PermitAll annotations?

On the class level, you can implement @RolesAllowed and @PermitAll. Annotations to methods take precedence over those to classes.

Conclusion

In this blog, we learned about the dropwizard authentication implementation and the different types of authentication methods available in dropwizard. We have also discussed the feature integrated with the dropwizard authentication.

To learn more about dropwizard, check out the following articles.

Dropwizard Commands

Dropwizard Dependency Injection

Dropwizard Migrations

Dropwizard Forms

To learn more about DSA, competitive coding, and many more knowledgeable topics, and please look into the guided paths on Coding Ninjas Studio. Also, you can enroll in our courses and check out the mock test and problems available to you. Please check out our interview experiences and interview bundle for placement preparations.

Live masterclass