Dropwizard:BasicAuth [英] Dropwizard: BasicAuth

查看:80
本文介绍了Dropwizard:BasicAuth的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Dropwizard身份验证0.9.0-SNAPSHOT

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

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

我收到以下异常

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

! 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?

身份验证器类

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

推荐答案

要使auth与0.9+配合使用,您需要执行以下操作.您可以以更改集为例.

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

包括依赖项.

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

}

基本身份验证器

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

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

最后在您的资源中使用它

Finally use it in your resource

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

这篇关于Dropwizard:BasicAuth的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆