【问题标题】:What Jersey security annotation can be used to permit anonymous only access to an endpoint?什么 Jersey 安全注释可用于允许匿名访问端点?
【发布时间】:2017-05-04 21:31:54
【问题描述】:

我有一个注册端点,我只希望匿名用户能够访问。换句话说,我只希望未经身份验证的用户能够 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());
        }
    }
}

【问题讨论】:

    标签: java jersey jersey-2.0 dropwizard


    【解决方案1】:

    没有这样的注释。这个用例并不真正适合授权的语义。您可以使用的一种解决方法是注入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

    【讨论】:

      猜你喜欢
      • 2019-11-23
      • 2015-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-24
      • 1970-01-01
      相关资源
      最近更新 更多