RESTlet Authorization Filter

点点圈 提交于 2019-12-07 09:15:32

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