[原创]使用Acegi时获取用户信息的几个函数

Acegi框架通过ThreadLocal存放用户信息,因此可以通过以下函数获取相关信息:

  /**
   * 取得当前用户名
   * 
@return
   
*/

  
public static String getUsername(){
    Context context
=ContextHolder.getContext();
    
if(context!=null){
      
if(context instanceof SecureContext){
        SecureContext sc
=(SecureContext)context;
        Authentication auth
=sc.getAuthentication();
        
if(auth!=null){
          Object principal
=auth.getPrincipal();
          
if(principal instanceof UserDetails) {
            
return ((UserDetails)principal).getUsername();
          }
else{
            
return principal.toString();
          }

        }

      }

    }

    
return null;
  }

  
/**
   * 取得当前用户密码
   * 
@return
   
*/

  
public static String getPassword(){
    Context context
=ContextHolder.getContext();
    
if(context!=null){
      
if(context instanceof SecureContext){
        SecureContext sc
=(SecureContext)context;
        Authentication auth
=sc.getAuthentication();
        
if(auth!=null){
          Object principal
=auth.getPrincipal();
          
if(principal instanceof UserDetails) {
            
return ((UserDetails)principal).getPassword();
          }
else{
            
return null;
          }

        }

      }

    }

    
return null;
  }

  
/**
   * 取得当前用户session id
   * 
@return sessionid or null
   
*/

  
public static String getSessionID(){
    Context context
=ContextHolder.getContext();
    
if(context!=null){
      
if(context instanceof SecureContext){
        SecureContext sc
=(SecureContext)context;
        Authentication auth
=sc.getAuthentication();
        
if(auth!=null){
          Object details
=auth.getDetails();
          
if(details instanceof WebAuthenticationDetails) {
            
return ((WebAuthenticationDetails)details).getSessionId();
          }
else{
            
return null;
          }

        }

      }

    }

    
return null;
  }

posted on 2006-03-03 16:17 一餐三碗 阅读(2787) 评论(4)  编辑  收藏 所属分类: Tips

评论

# re: [原创]使用Acegi时获取用户信息的几个函数 2006-03-03 19:17 dylan  回复  更多评论   

ContextHolder从0.9开始已经取消了

# re: [原创]使用Acegi时获取用户信息的几个函数 2006-03-05 13:06 一餐三碗  回复  更多评论   

@dylan
呵呵,我这个是针对0.8.3版本的,在新的版本里应该也有对应的方法。

# re: [原创]使用Acegi时获取用户信息的几个函 2006-06-16 16:57 liunq  回复  更多评论   

呵呵

# re: [原创]使用Acegi时获取用户信息的几个函数 2007-01-01 13:26 itspy  回复  更多评论   

1.0有如下方法

SecurityContext ctx = SecurityContextHolder.getContext();
Authentication auth = ctx.getAuthentication();

只有注册用户登录后才能发表评论。


网站导航: