MickeyThreeSheds
MickeyThreeSheds

Reputation: 1016

Using a JWT token with dropwizard? I already have db auth, but am confused about utilizing tokens

I have the following Authenticator class for DB authentication:

public class DBAuthentication implements Authenticator<BasicCredentials, User> {

    private UserDAO userDAO;

    public DBAuthentication(UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    @Override
    public Optional<User> authenticate(BasicCredentials credentials) throws AuthenticationException{
       return userDAO.findByUsernamePassword(credentials.getUsername(), credentials.getPassword());
    }
}

and then when I want to authenticate against a resource, I simply do :

@GET
@Produces(MediaType.TEXT_PLAIN)
@Path("/secured")
@UnitOfWork
public String aliveSecure(@Auth User user)
{
    return "working.";
}

Which is a simple, authenticated method - and that works well... However, let's assume I want to have a user sign in, then get a token they can use for future requests, until the token expires... I would ASSUME (and correct me if I am wrong) that I would do something like have a resource, which would take the credentials, then return the token inside a response, for storage on the client end - and that is fine... but if I do that, how would I later authenticate against the token?

Upvotes: 3

Views: 4901

Answers (1)

Hendrikvh
Hendrikvh

Reputation: 545

You are correct -- You will add an endpoint which issues JWT tokens once authenticated, and then annotate your other protected resources to use JWT authentication.

Check out dropwizard-auth-jwt, which adds JWT support to Dropwizard. There is an example on how to use it in their examples directory on Github.

Specifically look at the SecuredResource class, which can both issue a token as well as validate it.

You can for instance just extend your aliveSecure method to issue a JWT token.

I made an example project available at on Github which uses basic auth to issue tokens, and @Roles with JWTs.

Upvotes: 5

Related Questions