play secure模块 验证和授权管理

来源:互联网 发布:python 十分钟 编辑:程序博客网 时间:2024/05/16 12:49
参考:http://www.playframework.org/documentation/1.2.3/secure

Play Secure模块放置在play安装目录\modules\secure下,包含在play标准的发布包中。简单的Secure模块被设计用来帮助用户在应用程序中提供验证和授权管理。它提供了一个简单的控制器controllers.Secure,在里面定义了一些拦截器,你能很容易地使用@With注解把这些拦截器加到自己的控制器中。

启用Secure模块:
在/conf/dependencies.yml文件中增加如下内容:
Xml代码  收藏代码
  1. require:  
  2.     - play -> secure  

导入Secure模块的默认路由:
导入Secure模块的默认路由并不是必须的,用户可以定义自己的路由,也可以混合2者一起使用。
在conf/routes中通过如下命令导入默认的模块路由:
Xml代码  收藏代码
  1. # Import Secure routes  
  2. *      /                module:secure  

这里被导入的路由内容如下:
Xml代码  收藏代码
  1. # import these default routes as :  
  2. # *         /               module:secure  
  3. # ~~~~  
  4.   
  5. GET         /login          Secure.login  
  6. POST        /login          Secure.authenticate  
  7. GET         /logout         Secure.logout  

使用拦截器保护controller:
如下使用@With注解来保护控制器(必须验证通过才能使用该控制器)
Java代码  收藏代码
  1. @With(Secure.class)  
  2. public class Application extends Controller {  
  3.       
  4.     public static void index() {  
  5.         render();  
  6.     }  
  7. }  

自定义验证方法:
默认情况下,登陆页面接受所有的用户名和密码。为了给应用程序增加安全保护,只需要按如下步骤定制下它。
  • 在controllers包下创建一个继承自controllers.Secure.Security的方法
  • 重写authenticate(String username, String password)方法
  • 也可以重写其他方法,如onAuthenticated, onDisconnected来修改应用程序行为

Java代码  收藏代码
  1. package controllers;  
  2.    
  3. public class Security extends Secure.Security {  
  4.       
  5.     static boolean authenticate(String username, String password) {  
  6.         User user = User.find("byEmail", username).first();  
  7.         return user != null && user.password.equals(password);  
  8.     }  
  9. }  

访问验证通过的用户:
使用Security.connected方法来取得验证通过的用户
Java代码  收藏代码
  1. @With(Secure.class)  
  2. public class Application extends Controller {  
  3.       
  4.     public static void index() {  
  5.         String user = Security.connected();  
  6.         render(user);  
  7.     }  
  8. }  

增加授权检查 check注解:
可以使用@check注解来告诉Secure模块,检查当前连接的用户是否有操作控制器、或者其中的方法的权限。
Java代码  收藏代码
  1. @With(Secure.class)  
  2. public class Application extends Controller {   
  3.    …  
  4.      
  5.    @Check("isAdmin")  
  6.    public static void delete(Long id) {  
  7.        …  
  8.    }  
  9. }  

默认情况下,secure模块会一直检查所有checks,你可以通过在自己的Security类中重写方法来修改默认行为。
Java代码  收藏代码
  1. package controllers;  
  2.    
  3. public class Security extends Secure.Security {  
  4.     …  
  5.       
  6.     static boolean check(String profile) {  
  7.         User user = User.find("byEmail", connected()).first();  
  8.         if ("isAdmin".equals(profile)) {  
  9.             return user.admin;  
  10.         }  
  11.         else {  
  12.             return false;  
  13.         }  
  14.     }      

0 0