RESTlet授权filter
我正在开发一个RESTlet API(JAVA),我创建了一个自定义授权filter,在将其传递给我的路由器之前运行所有请求。 在我的请求中,我总是将会话ID作为请求属性传递,例如
http://localhost:8080/myAPI/{sid}/someResource/
现在,在扩展ServerResource的函数中,我可以做这样的事情来轻松提取{sid} :
String sid = (getRequestAttributes().containsKey("sid")) ? getRequestAttributes().get("sid").toString() : "";
我的问题是,在我的授权函数中,它扩展了Filter (授权函数不是通过路由器调用,而是在我的main createInboundRoot()函数中调用),我不能使用相同的方法来提取{sid} 。 我使用request.getResourceRef()。getSegments()的字符串操作创建了一个变通方法,但是必须有更好的方法吗?
任何帮助将不胜感激!
谢谢
您可以为ServerResource
任何子级创建公共父类 。 像这样:
public class CommonParentResource extends ServerResource { // class definition }
然后重写其中ServerResource类的doInit()
方法。
public class CommonParentResource extends ServerResource { public void doInit() { boolean authorized=false; String sid = getRequestAttributes().containsKey("sid") ? (String)getRequestAttributes().get("sid") : StringUtils.EMPTY; // Authorization logic here. if(!authorized)//after authorization process completed. { getResponse().setStatus(Status.CLIENT_ERROR_UNAUTHORIZED); getResponse().setEntity(/*Representation carrrying message for unauthorized user*/); } } }
现在,要执行此授权检查的任何新的ServerResource
子类都必须扩展此CommonParentResource
类。 喜欢这个:
public class FriendsListResource extends CommonParentResource { @Get //...... }
这里有两点很重要:
-
在调用任何使用
@Get
/@Post
/注释的方法之前调用ServerResource
的任何子类的doInit()
-
(注意)如果您不使用此声明:
getResponse().setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
即如果你没有设置对错误的响应 状态 ,那么用
@Get
/@Post
/@Put
/ …注释的方法将被调用! 但是,如果您的程序将响应的状态设置为错误状态,则@Get
/@Post
/@Put
/ …将不会执行,最终用户将看到由以下内容表示的错误消息:getResponse().setEntity(/*Representation carrrying message for unauthorized user*/);