在playframework中提供带身份验证的静态文件

时间:2011-10-26 17:48:52

标签: playframework

是否有一种简单/内置的方法让控制器检查连接是否有权访问静态文件而不是服务器(使用数据库查找),然后在需要时提供访问权。

有大型视频文件,我想a)检查是否允许用户访问该文件,b)如果用户被授权我想记录视频已被观看。

1 个答案:

答案 0 :(得分:7)

有两种方法可以做到这一点。

第一个也是最优雅的方式是使用Play插件功能。

您可以在How to extend the playframework?找到更多信息 这是javadoc: http://www.playframework.org/documentation/api/1.2.3/play/PlayPlugin.html

第二个是从路径

提供文件

如果文件是基于路由/控制器的,那么您可以像保护其他任何控制器一样保护它们。如果我错了,有人会纠正我。

我会做类似的事情(注意这段代码尚未经过测试):

使用@With(Secure.class)保护

public static void getImage() {
    File file = new File( "~/image.png" );
    response.contentType = "image/png";
    renderBinary( file );
}

然后路线

GET     /static/image1    Application.getImage

或者你可以让它更优雅。

GET     /static/image/{fileName}   Application.getImage
GET     /static/image/{id}         Application.getImageById

   public static void getImage(String fileName) {
        File file = new File( "~/" + fileName );
        response.contentType = "image/png";
        renderBinary( file );
    }

或者更进一步。

public static void getImage( String fileName, String username ) {
    File file = new File( "~/" + fileName );

    if ( file.exists() ) {
        User user = User.find( "byName", username ).fetch();
        user.watch = true;
        user.save();

        response.contentType = "image/png";
        renderBinary( file );
    }
}

如果文件不存在,显然你需要一些特技和捕获。

祝你好运。