我有一个RESTful服务,几乎所有端点都有一个url参数userId
。
我有一个单独的DynamoDB表,该表存储了被列入黑名单的用户,并且希望这些用户中的任何一个的所有请求都被删除(即返回401代码),否则继续进行。
我的解决方法是将OncePerRequestFilter
实现并注册为bean,但是我不确定100%如何实现(在doFilterInternal
内),或者是否有更好的方法实现。
到目前为止我所拥有的:
public class BlacklistedFilter extended OncePerRequestFilter {
static final String TABLE_NAME = "banned-users";
// Instantiate dynamo connection with some service provider
this.dynamoService = new dynamoService('TABLE_NAME');
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
// Retrieve path variable `userId`
final Map<String, String> pathVariables = (Map<String, String>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
final String userId = pathVariables.get('userId');
Item item = this.dynamoService.getUser(userId);
// This is doing: dynamoClient.getTable(TABLE_NAME).getItem('userId', userId)
// What do I do here????
if (item != null) {
// Proceed to original request
} else {
// RETURN 401
}
filterChain.doFilter(request, response);
}
}
如果可行,那就足够了。您可以创建单独的方法。如果不经常更改,则结果为cache。
@Cacheable("isBlacklisted")
public boolean isBlacklisted(String userId) {
Item item = this.dynamoService.getUser(userId);
return item != null;
}