参考:http://www.playframework.org/documentation/1.2.3/secure
Play Secure模块放置在play安装目录modulessecure下,包含在play标准的发布包中。简单的Secure模块被设计用来帮助用户在应用程序中提供验证和授权管理。它提供了一个简单的控制器controllers.Secure,在里面定义了一些拦截器,你能很容易地使用@With注解把这些拦截器加到自己的控制器中。
启用Secure模块:
在/conf/dependencies.yml文件中增加如下内容:
require: - play -> secure
导入Secure模块的默认路由:
导入Secure模块的默认路由并不是必须的,用户可以定义自己的路由,也可以混合2者一起使用。
在conf/routes中通过如下命令导入默认的模块路由:
# Import Secure routes * / module:secure
这里被导入的路由内容如下:
# import these default routes as : # * / module:secure # ~~~~ GET /login Secure.login POST /login Secure.authenticate GET /logout Secure.logout
使用拦截器保护controller:
如下使用@With注解来保护控制器(必须验证通过才能使用该控制器)
@With(Secure.class) public class Application extends Controller { public static void index() { render(); } }
自定义验证方法:
默认情况下,登陆页面接受所有的用户名和密码。为了给应用程序增加安全保护,只需要按如下步骤定制下它。
- 在controllers包下创建一个继承自controllers.Secure.Security的方法
- 重写authenticate(String username, String password)方法
- 也可以重写其他方法,如onAuthenticated, onDisconnected来修改应用程序行为
package controllers; public class Security extends Secure.Security { static boolean authenticate(String username, String password) { User user = User.find("byEmail", username).first(); return user != null && user.password.equals(password); } }
访问验证通过的用户:
使用Security.connected方法来取得验证通过的用户
@With(Secure.class) public class Application extends Controller { public static void index() { String user = Security.connected(); render(user); } }
增加授权检查 check注解:
可以使用@check注解来告诉Secure模块,检查当前连接的用户是否有操作控制器、或者其中的方法的权限。
@With(Secure.class) public class Application extends Controller { … @Check("isAdmin") public static void delete(Long id) { … } }
默认情况下,secure模块会一直检查所有checks,你可以通过在自己的Security类中重写方法来修改默认行为。
package controllers; public class Security extends Secure.Security { … static boolean check(String profile) { User user = User.find("byEmail", connected()).first(); if ("isAdmin".equals(profile)) { return user.admin; } else { return false; } } }