什么 Jersey 安全注释可用于允许仅匿名访问端点?

What Jersey security annotation can be used to permit anonymous only access to an endpoint?

我有一个只希望匿名用户能够访问的注册端点。换句话说,我只希望未经身份验证的用户能够 POST 到端点。执行此操作的最佳方法是什么?

@Path("/accounts")
public class AccountResource {

    @Inject
    private AccountService accountService;

    @DenyAll
    @POST
    public void register(CreateAccountJson account) {
        try {
            accountService.registerUserAndCreateAccount(account.getEmail(),
                account.getPassword());
        } catch (RegistrationException e) {
            throw new BadRequestException(e.getMessage());
        }
    }
}

没有这样的注释。这个用例并不真正符合授权的语义。您可以使用的一种解决方法是注入 SecurityContext。只需检查是否有 Principal。如果不是,则没有经过身份验证的用户。如果有,那么你可以发送一个 404

@POST
public void register(@Context SecurityContext context, CreateAccountJson account) {

    if (context.getUserPrincipal() != null) {
        throw new NotFoundException();
    }
    ...
}

更新

如果您有很多这样的资源方法,最好使用名称绑定的过滤器。例如

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface NonAuthenticated {}

@NonAuthenticated
// Perform before normal authorization filter
@Priority(Priorities.AUTHORIZATION - 1)
public class NonAuthenticatedCheckFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext request) {
        final SerurityContext context = request.getSecurityContext();
        if (context.getUserPrincipal() != null) {
            throw new ForbiddenException();
        }
    }
}

@POST
@NonAuthenticated
public void register(CreateAccountJson account) { }

// register the Dw
environment.jersey().register(NonAuthenticatedCheckFilter.class);

有关 Jersey 过滤器的更多信息,请参阅 Jersey 文档中的 Filter and Interceptors