Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dropwizard: BasicAuth

Using Dropwizard Authentication 0.9.0-SNAPSHOT

I want to check the credentials against database user (UserDAO).

I get the following exception

! org.hibernate.HibernateException: No session currently bound to execution context

How to bind the session to the Authenticator? Or are there better ways to check against the database user?

The Authenticator Class

package com.example.helloworld.auth;

import com.example.helloworld.core.User;
import com.example.helloworld.db.UserDAO;
import com.google.common.base.Optional;
import io.dropwizard.auth.AuthenticationException;
import io.dropwizard.auth.Authenticator;
import io.dropwizard.auth.basic.BasicCredentials;

public class ExampleAuthenticator implements Authenticator<BasicCredentials, User> {
    UserDAO userDAO;

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

    @Override
    public Optional<User> authenticate(BasicCredentials credentials) throws AuthenticationException {
        Optional<User> user;

        user = (Optional<User>) this.userDAO.findByEmail(credentials.getUsername());


        if ("secret".equals(credentials.getPassword())) {
            return Optional.of(new User(credentials.getUsername()));
        }
        return Optional.absent();
    }
}

The Application Class

@Override
public void run(HelloWorldConfiguration configuration, Environment environment) throws Exception {
    final UserDAO userDAO = new UserDAO(hibernate.getSessionFactory());

    environment.jersey().register(new AuthDynamicFeature(
        new BasicCredentialAuthFilter.Builder<User>()
                .setAuthenticator(new ExampleAuthenticator(userDAO))
                .setAuthorizer(new ExampleAuthorizer())
                .setRealm("SUPER SECRET STUFF")
                .buildAuthFilter()));
    environment.jersey().register(RolesAllowedDynamicFeature.class);
    //If you want to use @Auth to inject a custom Principal type into your resource
    environment.jersey().register(new AuthValueFactoryProvider.Binder(User.class));

    environment.jersey().register(new UserResource(userDAO));
like image 653
Daniel Ozean Avatar asked Sep 19 '15 17:09

Daniel Ozean


2 Answers

To get auth to work with 0.9+ you need the following. You can refer to this particular changeset as an example.

Include the dependency.

<dependency>
    <groupId>io.dropwizard</groupId>
    <artifactId>dropwizard-auth</artifactId>
    <version>${dropwizard.version}</version>
</dependency>

Register auth related stuff.

private void registerAuthRelated(Environment environment) {
    UnauthorizedHandler unauthorizedHandler = new UnAuthorizedResourceHandler();
    AuthFilter basicAuthFilter = new BasicCredentialAuthFilter.Builder<User>()
        .setAuthenticator(new BasicAuthenticator())
        .setAuthorizer(new UserAuthorizer())
        .setRealm("shire")
        .setUnauthorizedHandler(unauthorizedHandler)
        .setPrefix("Basic")
        .buildAuthFilter();

    environment.jersey().register(new AuthDynamicFeature(basicAuthFilter));
    environment.jersey().register(RolesAllowedDynamicFeature.class);
    environment.jersey().register(new AuthValueFactoryProvider.Binder(User.class));

    environment.jersey().register(unauthorizedHandler);

}

A basic authenticator

public class BasicAuthenticator<C, P> implements Authenticator<BasicCredentials, User> {
    @Override
    public Optional<User> authenticate(BasicCredentials credentials) throws AuthenticationException {
        //do no authentication yet. Let all users through
        return Optional.fromNullable(new User(credentials.getUsername(), credentials.getPassword()));
    }
}

UnAuthorizedHandler

public class UnAuthorizedResourceHandler implements UnauthorizedHandler {

    @Context
    private HttpServletRequest request;

    @Override
    public Response buildResponse(String prefix, String realm) {
        Response.Status unauthorized = Response.Status.UNAUTHORIZED;
        return Response.status(unauthorized).type(MediaType.APPLICATION_JSON_TYPE).entity("Can't touch this...").build();
    }

    @Context
    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }
}

Authorizer

public class UserAuthorizer<P> implements Authorizer<User>{
    /**
     * Decides if access is granted for the given principal in the given role.
     *
     * @param principal a {@link Principal} object, representing a user
     * @param role      a user role
     * @return {@code true}, if the access is granted, {@code false otherwise}
     */
    @Override
    public boolean authorize(User principal, String role) {
        return true;
    }
}

Finally use it in your resource

@GET
public Response hello(@Auth User user){
    return Response.ok().entity("You got permission!").build();
}
like image 107
Nasir Avatar answered Sep 28 '22 08:09

Nasir


You're going to need code in your Application class that looks like this

environment.jersey().register(AuthFactory.binder(new BasicAuthFactory<>(
       new ExampleAuthenticator(userDAO), "AUTHENTICATION", User.class)));

Then you can use the @Auth tag on a User parameter for a method and any incoming authentication credentials will hit the authenticate method, allowing you to return the correct User object or absent if the credentials are not in your database.

EDIT: Works for Dropwizard v0.8.4

like image 42
Rohan Avatar answered Sep 28 '22 08:09

Rohan