Dropwizard 授权用户

Dropwizard auth users

我正在做一些关于 drop-wizard 安全和身份验证的研究。这是我使用 http://howtodoinjava.com/dropwizard/dropwizard-basic-auth-security-example/.

的 link

我的问题是如何实际创建新用户,因为 VALID_USERS 是静态的,无法更改。我正在考虑创建一个数据库,它将由包含用户名和角色 ex 的用户对象组成。行政。 (我不需要密码)但是我很困惑我会 return。在他们的示例中,他们 returned Optional.of(new User(credentials.getUsername(), VALID_USERS.get(credentials.getUsername()))); 我会 return 一个用户对象吗?

本质上,我想通过用户名对用户进行身份验证,并赋予他们授权角色。管理员,基本。但我想我对如何生成用户及其角色列表感到困惑。我正在考虑制作一个数据库,但我不确定我将如何实现它。

    public class AppBasicAuthenticator implements Authenticator<BasicCredentials, User> 
{
    private static final Map<String, Set<String>> VALID_USERS = ImmutableMap.of(
        "guest", ImmutableSet.of(),
        "user", ImmutableSet.of("USER"),
        "admin", ImmutableSet.of("ADMIN", "USER")
    );

    @Override
    public Optional<User> authenticate(BasicCredentials credentials) throws AuthenticationException 
    {
        if (VALID_USERS.containsKey(credentials.getUsername()) && "password".equals(credentials.getPassword())) 
        {
            return Optional.of(new User(credentials.getUsername(), VALID_USERS.get(credentials.getUsername())));
        }
        return Optional.empty();
    }
}

在最新版本的 DropWizard 中,您会发现可以同时进行身份验证和授权。简而言之,前者指示 DropWizard 在用户尝试访问资源或提供其他身份检查时,如果您使用基本身份验证,则要求用户提供凭据。后者允许根据用户的角色授予用户对各种资源的访问权限。

存储用户数据和角色的方式多种多样。示例包括您提到的数据库、LDAP 服务器和第三方身份管理系统。

如果您对基本身份验证感兴趣,可以看看我的示例here. A database is used to store user's credentials. Also, here is my little bit dated tutorial on DropWizard authentication。最新版本的代码在上述示例应用程序中。

如果只实现身份验证,您可以跳过添加角色和注册授权者。要添加授权,您可以将角色集合添加到您的用户实体,并使用 @RolesAllowed 和 @PermitAll 等注释以及 Authorizer 实现 grant/deny 访问您的资源。

DropWizard 身份验证文档的 link 是 here

欢迎在评论中提出更多问题,祝你好运。