Dropwizard:BasicAuth

时间:2015-09-19 17:45:58

标签: basic-authentication dropwizard

使用Dropwizard Authentication 0.9.0-SNAPSHOT

我想检查针对数据库用户(UserDAO)的凭据。

我收到以下异常

  

! org.hibernate.HibernateException:当前没有绑定的会话   执行上下文

如何将会话绑定到Authenticator? 或者有更好的方法来检查数据库用户?

身份验证员类

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();
    }
}

应用程序类

@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));

2 个答案:

答案 0 :(得分:5)

要让auth使用0.9+,您需要以下内容。您可以参考此特定changeset作为示例。

包含依赖项。

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

注册auth相关内容。

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);

}

基本身份验证器

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;
    }
}

认证器

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;
    }
}

最后在你的资源中使用它

@GET
public Response hello(@Auth User user){
    return Response.ok().entity("You got permission!").build();
}

答案 1 :(得分:1)

在从0.9开始的最新版本中,您可以在资源类方法中使用“@ Context”注释,如下所示:

@RolesAllowed("EMPLOYEE")
    @Path("/emp")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getEmployeeResponse(@Context SecurityContext context) {
        SimplePrincipal sp = (SimplePrincipal) context.getUserPrincipal();
        return Response.ok("{\"Hello\": \"Mr. " + sp.getUsername() + "\"( Valuable emp )}").build();

    }