在Java Web应用程序中实现协作认证

11 java authentication web-applications

我需要构建一个基于Java的Web应用程序,其中资源只有在该资源的所有授权用户都登录时才可用.此外,如果任何授权用户注销,该资源将不再可用于任何他们.

资源可以是任何类型(html页面,pdf文档,电子表格等)

是否有任何现有的认证标准/协议支持这种类型的要求,或者我是从头开始构建这个?

rar*_*dea 1

如果您不限于使用特定的 Web 框架,请随意尝试以下基于 jersey 的过滤器实现。请注意,您仍然需要添加大量自定义代码来处理“集体身份验证”的逻辑,因为 jersey 仅提供了所需的基本工具,并且没有显式实现整个概念。从高层次上看,您可以这样做:

class AuthorizationProvider {

    public void authenticate(ContainerRequestContext requestContext) {

        // Here you would need to query your database to get the Collection of Users belonging 
        // to the "Collective" Role. You would then check if they are all logged in.
        // A really abstract version would look like this, assuming you've already queried the DB
        // and have a reference to the above mentioned Collection.

        if (collectiveUsers.size == collectiveUsers.stream().filter(User::isLoggedIn).count()) {
            return true;
        }
        return false;
    }
}

class AuthorizationRequestFilter implements ContainerRequestFilter {

    private final AuthorizationProvider authorizationProvider;

    @Override
    public void filter(ContainerRequestContext requestContext) {

        if (authorizationProvider.authenticate(requestContext)) {
            // serve whatever it is you want to serve if all required users are logged in
        } else {
            // otherwise reject the request
            requestContext.abortWith(Response
                .status(Response.Status.UNAUTHORIZED)
                .entity("Resource available only after collective login")
                .build());
        }
    }
}

@ApplicationPath("/")
class MyApplication extends ResourceConfig {

    public MyApplication() {
        // Register the filter
        register(AuthorizationRequestFilter.class);
    }
}
Run Code Online (Sandbox Code Playgroud)

除此之外,您还需要处理登录部分。您可以为这些特定用户分配集体角色,并且只要他们成功通过登录身份验证,您就可以将他们标记为已登录。

如果满足上述所有条件,则只有当所有“集体”用户都登录时,您才应该能够成功提供“仅限集体”页面。

这还涵盖了以下部分:如果这些用户之一注销,则将状态存储在数据库中(使用 isLoggedIn = false 标记集体用户)。所以从现在开始,每当有人请求该页面时,它都会返回 Unauthorized。

相反,如果有人注销,您也可以尝试实现 SSE(服务器发送事件)来主动更新前端部分。这样,即使有人之前已经成功获取了该页面,该页面也会被主动禁用。

容器请求过滤器源码和示例,供参考,jersey docs