2006-12-08

Spring框架下实现基于组的用户权限管理

来源: 本站收集整理 作者:佚名 评论 0 条
  在几乎所有的web应用中都需要对访问者(用户)进行权限治理, 因为我们希望某些页面只对特定的用户开放, 以及某些操作只有符合身份的用户才能进行。这之中涉及到了身份验证和权限治理. 只有单用户系统和多用户单权限系统才不需要权限治理。

  在本文中, 使用了基于组的权限治理, 并在Spring框架下利用HandlerInterceptorAdapter和Hibernate进行实现。

  User的结构是:

public class User {
 private int id;
 private String name;
 private String password;
 private Set<String> groups = new HashSet<String>();
}

  UserGroup表:

  user:intgroup:String使用联合主键, 在Java中没有对应的类。

  Hibernate映射文件是:

<hibernate-mapping auto-import="true" default-lazy="false">
 <class name="net.ideawu.User" table="User">
 <cache usage="read-write" />
 <id name="id" column="id">
  <generator class="native"/>
 </id>
 <property name="name" column="name"/>
 <property name="password" column="password"/>
 <set name="groups" table="UserGroup" cascade="save-update" lazy="false">
  <key column="user" />
  <element column="`group`" type="string" />
 </set>
 </class>
</hibernate-mapping>

  一切的身份验证交给一个继续HandlerInterceptorAdapter的类来做:

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.UrlPathHelper;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
...
public class AuthorizeInterceptor extends HandlerInterceptorAdapter {
 private UrlPathHelper urlPathHelper = new UrlPathHelper();
 private PathMatcher pathMatcher = new AntPathMatcher();
 private Properties groupMappings;
 /** * Attach URL paths to group. */
 public void setGroupMappings(Properties groupMappings) {
  this.groupMappings = groupMappings;
 }
 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  String url = urlPathHelper.getLookupPathForRequest(request);
  String group = lookupGroup(url);
  // 找出资源所需要的权限, 即组名
  if(group == null){
   // 所请求的资源不需要保护.
   return true;
  }
  // 假如已经登录, 一个User实例被保存在session中.
  User loginUser = (User)request.getSession().getAttribute("loginUser");
  ModelAndView mav = new ModelAndView("system/authorizeError");
  if(loginUser == null){
   mav.addObject("errorMsg", "你还没有登录!");
   throw new ModelAndViewDefiningException(mav);
  }else{
   if(!loginUser.getGroups().contains(group)){
共2页: 上一页 1 [2] 下一页
(本文仅表明作者个人观点,不代表本站及其管理员立场.) 推荐 收藏 投稿 打印 返回 关闭
上一篇:C#中使用存储过程中的返回值  
下一篇:C#实现类似qq的屏幕截图程序
    评论加载中…
 推荐文章
     

网站首页  -  网站地图 -   站长论坛  -  网站投稿  -    -  网站管理
Copyright © 2008 芜湖站长站 All Rights Reserved 皖ICP备07500611号