在 Quarkus 中使用自定义身份提供商

c0f*_*lex 3 quarkus quarkus-jpa

在我当前的项目中,我们将用户登录信息存储在 MongoDB 集合中。我们希望实现一种身份验证机制,根据存储在所述 MongoDB 中的信息检查请求中的凭据。有一个使用 JPA + Postgres执行此操作的教程,但没有关于以相同容量使用 MongoDB 的信息。我怀疑我需要为这种情况编写一个自定义 IdentityProvider。我尝试使用 JPA 身份提供程序作为基础,但看起来 security-jpa 源代码仅包含一个抽象身份提供程序,而实际的提供程序是使用黑魔法自动生成的。有没有人成功地将现有的 Quarkus 安全架构适应 MongoDB 或 security-jpa 未涵盖的其他任何内容?

c0f*_*lex 5

经过一些研究,我能够让一个习惯IdentityProvider发挥作用。这是一个非常简单的演示(没有任何 MongoDB 逻辑):

@ApplicationScoped
public class DemoIdentityProvider implements IdentityProvider<UsernamePasswordAuthenticationRequest> {
    private static final Map<String, String> CREDENTIALS = Map.of("bob", "password124", "alice", "hunter2");

    @Override
    public Class<UsernamePasswordAuthenticationRequest> getRequestType() {
        return UsernamePasswordAuthenticationRequest.class;
    }

    @Override
    public Uni<SecurityIdentity> authenticate(UsernamePasswordAuthenticationRequest request,
                                              AuthenticationRequestContext authenticationRequestContext) {
        if (new String(request.getPassword().getPassword()).equals(CREDENTIALS.get(request.getUsername()))) {
            return Uni.createFrom().item(QuarkusSecurityIdentity.builder()
                .setPrincipal(new QuarkusPrincipal(request.getUsername()))
                .addCredential(request.getPassword())
                .setAnonymous(false)
                .addRole("admin")
                .build());
        }
        throw new AuthenticationFailedException("password invalid or user not found");
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,为了访问QuarkusSecurityIdentityquarkus-security扩展需要作为依赖项包含在pom.xml

<dependency>
  <groupId>io.quarkus</groupId>
  <artifactId>quarkus-security</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)

此外,quarkus.http.auth.basic=true需要添加application.properties身份提供者才能与基本身份验证一起使用。