RESTlet Authorization Filter

帅比萌擦擦* 提交于 2019-12-08 05:46:09

问题


I am developing a RESTlet API (JAVA), and I've created a custom authorization filter that I run all requests through before passing it to my router. In my requests I always pass the session ID as a request attribute, e.g.

    http://localhost:8080/myAPI/{sid}/someResource/

Now, in my functions that extends ServerResource, I can do something like this to easily extract that {sid}:

    String sid = (getRequestAttributes().containsKey("sid")) ? getRequestAttributes().get("sid").toString() : "";

My problem is, in my authorization function, which extends Filter (the authorization function is not called via a router, but is called in my main createInboundRoot() function), I cannot use the same method to extract the {sid}. I've created a workaround using string manipulation of request.getResourceRef().getSegments(), but there must be a better way?

Any help will be appreciated!

Thanks


回答1:


You can create a common parent class for any child of ServerResource. like this:

public class CommonParentResource extends ServerResource
{
    // class definition
}

And then override the doInit() method of the ServerResource class in it.

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*/);
        }
    }
}

Now any new child class of ServerResource that you want to perform this authorization check, must extend this CommonParentResource class. Like this:

public class FriendsListResource extends CommonParentResource
{
    @Get
    //......
}

Two points are important here:

  1. doInit() of any child class of ServerResource is called before calling any method annotated with @Get / @Post / ...

  2. (Caution) If you do not use this statement:

    getResponse().setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
    

    i.e. if you do not set status of response to an error, then methods annotated with @Get / @Post / @Put / ... will get called ! But if your program sets the status of the response to an error-status, then the @Get / @Post / @Put / ... will not get executed, and the end user will see the error message represented by:

    getResponse().setEntity(/*Representation carrrying message for unauthorized user*/);
    


来源:https://stackoverflow.com/questions/14395291/restlet-authorization-filter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!