MyException - 我的异常网
当前位置:我的异常网» 行业应用 » shiro中透过返回更多用户信息

shiro中透过返回更多用户信息

www.MyException.Cn  网友分享于:2013-01-02  浏览:0次
shiro中通过返回更多用户信息

 

 

shiro中通过返回更多用户信息

 

 

在重写的AuthorizingRealm中方法doGetAuthenticationInfo中传入封装的用户实体即可。

 

UserDetails userDetails=null;

 

                try {

                    userDetails = this.userDetailsService.loadUserByUsername(token1.getUsername());

                } catch (UsernameNotFoundException notFound) {

 

                    return null;

                }

 

AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(userDetails, userDetails.getPassword(),getName());

 

 

 

示例:

 

 

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package com.common.shrio;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.hanker.config.ConfigInfo;
import com.opensymphony.xwork2.ActionContext;
import core.apps.rbac.login.UserDetailsBean;
import core.session.filter.RemoteSessionRequest;
import core.session.manager.WebSession;
import core.session.manager.WebSessionManager;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UserDetailsService;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.web.subject.WebSubject;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import core.apps.rbac.entity.RoleSkillBTEntity;
import core.apps.rbac.manage.service.UserService;
import core.apps.rbac.vo.SelectRoleVO;
import core.db.dao.IBaseService;

import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 几个概念? 翻译不好,从官方上找来的原?. 如果不懂? 使用 “有道词典?��?来源于? http://shiro.apache.org/java-authentication-guide.html
 * 
 * Subject        Security specific user 'view' of an application user. It can be a human being, a third-party process, 
 *                 a server connecting to you application application, or even a cron job. Basically, it is anything or 
 *                 anyone communicating with your application.
 * 
 * Principals  A subjects identifying attributes. First name, last name, social security number, username
 * 
 * Credentials secret data that are used to verify identities. Passwords, Biometric data, x509 certificates,
 * 
 * Realms     Security specific DAO, data access object, software component that talkts to a backend data source. 
 *              If you have usernames and password in LDAP, then you would have an LDAP Realm that would communicate 
 *              with LDAP. The idea is that you would use a realm per back-end data source and Shiro would know how 
 *              to coordinate with these realms together to do what you have to do.
 * 
 * @author fq1798
 *
 */
public class ShiroDbRealm extends AuthorizingRealm {
   @Autowired
   private UserDetailsService userDetailsService;
   
   @Autowired(required = false)
   private UserService userService ;
   
   @Autowired(required = false)
   private IBaseService baseService ;

   @Override
   protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
      
      //得到 doGetAuthenticationInfo 方法中传入的凭证
UserDetails shiroUser = (UserDetails) principals.fromRealm(getName()).iterator().next();
      
      List<String> roleList = new ArrayList<String>();
      List<String> permissionList = new ArrayList<String>();
      String userName = shiroUser.getUsername();
//    if(StringUtils.equals("20160606", userName)) {
List<SelectRoleVO> selectedRoleList = new ArrayList();
      if(null!=shiroUser){
         selectedRoleList = this.userService.findUserRoleListbyUserId(shiroUser.getUsername(), true);
         if (null != selectedRoleList && selectedRoleList.size() > 0) {
         for(SelectRoleVO r: selectedRoleList){
            roleList.add(r.getRoleId());
//          List<RoleSkillBTEntity> roleSkillBTEntity = baseService.findObjects(RoleSkillBTEntity.class, "roleId", r.getRoleId());
            
String sql = "SELECT b.*,s.URL from s_rbac_roleskillb  b ,s_rbac_skill s WHERE b.SKILLID=s.SKILLID AND b.ROLEID='"+r.getRoleId()+"'";
              List<Map> branchArr = this.baseService.queryForJDBCList(sql);
            if (null != branchArr&& branchArr.size() > 0) {
                 for (Iterator<Map> it = branchArr.iterator(); it.hasNext();) {//遍历角色菜单
Map resource = it.next();
                         if (!"".equals(resource)&&resource!=null) {
                           permissionList.add(resource.get("URL")+"");
                        }
                 }
            }
         }
         }
         
      }
         SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
         
         //这个确定页面?<shiro:hasRole>标签的name的??
//       roleList.add("admin");
info.addRoles(roleList);
         //这个就是页面? <shiro:hasPermission> 标签的name的??
//       permissionList.add("/flex/rbac/getSkillMenuAndSkillsForShow.action");
//       permissionList.add("/flex/uifrm/index.jsp");
info.addStringPermissions(permissionList);
         return info;
   }

   
   /**
    * AuthenticationInfo represents a Subject's (aka user's) stored account information 
    * relevant to the authentication/log-in process only. 
    */
@Override
   protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
      
//    UsernamePasswordToken usernamePasswordToke = (UsernamePasswordToken)token;
//    
//    
//    String username = usernamePasswordToke.getUsername();
//    
//    
//    System.out.println("====================doGetAuthenticationInfo begin ==========================");
//    System.out.println("username: " + username);
//    System.out.print("password: ");
//    System.out.println(usernamePasswordToke.getPassword());
//    System.out.println("principal: " + usernamePasswordToke.getPrincipal());
//    System.out.println("======================doGetAuthenticationInfo end ========================");
//    
//    
//    /**
//     * Constructor that takes in a single 'primary' principal of the account, its corresponding hashed credentials, the salt used to hash the credentials, and the name of the realm to associate with the principals.
//     * This is a convenience constructor and will construct a PrincipalCollection based on the principal and realmName argument.
//     * 
//     * 
//     * Parameters:
//     * 
//     * principal - the 'primary' principal associated with the specified realm.
//     * hashedCredentials - the hashed credentials that verify the given principal.
//     * credentialsSalt - the salt used when hashing the given hashedCredentials
//     * realmName - the realm from where the principal and credentials were acquired.
//     */
//    if(StringUtils.equals("admin", username)) {
//       return new SimpleAuthenticationInfo(new ShiroUser("admin", "admin"), "admin", ByteSource.Util.bytes("admin"), getName());
//    } else if(StringUtils.equals("test", username)) {
//       return new SimpleAuthenticationInfo(new ShiroUser("test", "test"), "test", ByteSource.Util.bytes("test"), getName());
//    }
//    return null;
      // 获取基于用户名和密码的令牌
UsernamePasswordToken token1 = (UsernamePasswordToken) token;
            UserDetails userDetails=null;

                try {
                    userDetails = this.userDetailsService.loadUserByUsername(token1.getUsername());
                } catch (UsernameNotFoundException notFound) {

                    return null;
                }
            try {
               if (null != userDetails) {
                  AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(
                        userDetails, userDetails.getPassword(),
                        getName());
                  this.setSession("currentUser", userDetails);
                  this.setSession("ACEGI_SECURITY_LAST_USERNAME", userDetails.getUsername());
                  String weixinOrderDetailUrl = ConfigInfo.getPropertiesValue("weixinOrderDetailUrl");
                  this.setSession("weixinOrderDetailUrl", weixinOrderDetailUrl);
                  //分机号
this.setSession("EXTNO", "");
                  return authcInfo;
               }
            } catch (Exception e) {
               e.printStackTrace();
            }
            return null;// null时会在LoginController中抛出UnknownAccountException异常
}
   
   private void setSession(Object key, Object value) throws Exception{
      Subject currentUser = SecurityUtils.getSubject();
//    WebSessionManager webSession = new WebSessionManager();
//    webSession.createSession()
//    ActionContext ctx = ActionContext.getContext();
HttpServletRequest request1 =(HttpServletRequest) ((WebSubject)SecurityUtils.getSubject()).getServletRequest();  //ServletActionContext.getRequest();
HttpServletResponse response1 =(HttpServletResponse) ((WebSubject)SecurityUtils.getSubject()).getServletResponse();  //ServletActionContext.getRequest();
//    HttpServletRequest request2 =(HttpServletRequest) request1;
//    HttpServletRequest request = ServletActionContext.getRequest();
//    Map request3 = (Map)ActionContext.getContext().get("request");
Cookie[] cookies = request1.getCookies();

      UserDetailsBean agentUser =(UserDetailsBean)currentUser.getPrincipal();
      String username=    getCookieValue(cookies, "username");
      if(value instanceof UserDetails ){
         UserDetailsBean shiroUser = (UserDetailsBean) value;
         if(username==null||!username.equals(shiroUser.getUserId())){
            username=shiroUser.getUserId();
         }
         WebSession webSession=WebSessionManager.getInstance().getSession(username);
         if(webSession==null){

            webSession=WebSessionManager.getInstance().createSession(username);
         }
//       UserDetailsBean shiroUser = (UserDetailsBean) value;

webSession.setAttribute(username, value);

         webSession.getAttribute(username);
      }


//    if(value instanceof UserDetails ){
//
//
//    }
Object currentUserob= currentUser;
      String uk="request";
      String rk="response";
//    ByteArrayOutputStream out = new ByteArrayOutputStream();
//    ObjectOutputStream obj = new ObjectOutputStream(out);
//    for(int i = 0; i<10; i++) {
//       obj.writeObject(request1);
//    }
//    webSession.setAttribute(uk+username, out.toByteArray());
//    out = new ByteArrayOutputStream();
//    obj = new ObjectOutputStream(out);
//    for(int i = 0; i<10; i++) {
//       obj.writeObject(response1);
//    }
//    webSession.setAttribute(rk+username, out.toByteArray());
//    webSession.getAttribute(uk);
//    RemoteSessionRequest request =(RemoteSessionRequest) request2;
//          request.getSession().setAttribute(key+"",value);
//    request.getSession().getAttribute(key+"");
if (null != currentUser) {
         Session session = currentUser.getSession();
         if (null != session) {
            session.setAttribute(key, value);
         } 
      }
   }
   
   
   /**
    * 自定义Authentication对象,使得Subject除了携带用户的登录名外还可以携带更多信息.
    */
public static class ShiroUser implements Serializable {
      private static final long serialVersionUID = -1373760761780840081L;
      public String loginName;
      public String name;

      public ShiroUser(String loginName, String name) {
         this.loginName = loginName;
         this.name = name;
      }

      public String getName() {
         return name;
      }

      /**
       * 本函数输出将作为默认?<shiro:principal/>输出.
       */
@Override
      public String toString() {
         return loginName;
      }

//    /**
//     * 重载equals,只计算loginName;
//     */
//    @Override
//    public int hashCode() {
//       return HashCodeBuilder.reflectionHashCode(this, "loginName");
//    }
//
//    /**
//     * 重载equals,只比较loginName
//     */
//    @Override
//    public boolean equals(Object obj) {
//       return EqualsBuilder.reflectionEquals(this, obj, "loginName");
//    }
}
   private static String getCookieValue(Cookie[] cookies, String cookieName)
   {
      if (cookies == null) {
         return null;
      }
      for (int i = 0; i < cookies.length; i++) {
         Cookie cookie = cookies[i];
         if (cookieName.equals(cookie.getName())) {
            return cookie.getValue();
         }
      }
      return null;
   }
   
}

 

 

 

 

 

 

 

文章评论

旅行,写作,编程
旅行,写作,编程
 程序员的样子
程序员的样子
团队中“技术大拿”并非越多越好
团队中“技术大拿”并非越多越好
写给自己也写给你 自己到底该何去何从
写给自己也写给你 自己到底该何去何从
看13位CEO、创始人和高管如何提高工作效率
看13位CEO、创始人和高管如何提高工作效率
当下全球最炙手可热的八位少年创业者
当下全球最炙手可热的八位少年创业者
那些争议最大的编程观点
那些争议最大的编程观点
做程序猿的老婆应该注意的一些事情
做程序猿的老婆应该注意的一些事情
“懒”出效率是程序员的美德
“懒”出效率是程序员的美德
为啥Android手机总会越用越慢?
为啥Android手机总会越用越慢?
鲜为人知的编程真相
鲜为人知的编程真相
10个帮程序员减压放松的网站
10个帮程序员减压放松的网站
2013年中国软件开发者薪资调查报告
2013年中国软件开发者薪资调查报告
60个开发者不容错过的免费资源库
60个开发者不容错过的免费资源库
老程序员的下场
老程序员的下场
Web开发人员为什么越来越懒了?
Web开发人员为什么越来越懒了?
我的丈夫是个程序员
我的丈夫是个程序员
Java 与 .NET 的平台发展之争
Java 与 .NET 的平台发展之争
编程语言是女人
编程语言是女人
2013年美国开发者薪资调查报告
2013年美国开发者薪资调查报告
如何区分一个程序员是“老手“还是“新手“?
如何区分一个程序员是“老手“还是“新手“?
亲爱的项目经理,我恨你
亲爱的项目经理,我恨你
程序员的鄙视链
程序员的鄙视链
如何成为一名黑客
如何成为一名黑客
中美印日四国程序员比较
中美印日四国程序员比较
那些性感的让人尖叫的程序员
那些性感的让人尖叫的程序员
程序员最害怕的5件事 你中招了吗?
程序员最害怕的5件事 你中招了吗?
程序员眼里IE浏览器是什么样的
程序员眼里IE浏览器是什么样的
聊聊HTTPS和SSL/TLS协议
聊聊HTTPS和SSL/TLS协议
我跳槽是因为他们的显示器更大
我跳槽是因为他们的显示器更大
程序猿的崛起——Growth Hacker
程序猿的崛起——Growth Hacker
为什么程序员都是夜猫子
为什么程序员都是夜猫子
代码女神横空出世
代码女神横空出世
“肮脏的”IT工作排行榜
“肮脏的”IT工作排行榜
我是如何打败拖延症的
我是如何打败拖延症的
程序员的一天:一寸光阴一寸金
程序员的一天:一寸光阴一寸金
什么才是优秀的用户界面设计
什么才是优秀的用户界面设计
程序员都该阅读的书
程序员都该阅读的书
每天工作4小时的程序员
每天工作4小时的程序员
一个程序员的时间管理
一个程序员的时间管理
程序员应该关注的一些事儿
程序员应该关注的一些事儿
十大编程算法助程序员走上高手之路
十大编程算法助程序员走上高手之路
初级 vs 高级开发者 哪个性价比更高?
初级 vs 高级开发者 哪个性价比更高?
5款最佳正则表达式编辑调试器
5款最佳正则表达式编辑调试器
10个调试和排错的小建议
10个调试和排错的小建议
漫画:程序员的工作
漫画:程序员的工作
不懂技术不要对懂技术的人说这很容易实现
不懂技术不要对懂技术的人说这很容易实现
Google伦敦新总部 犹如星级庄园
Google伦敦新总部 犹如星级庄园
程序员必看的十大电影
程序员必看的十大电影
软件开发程序错误异常ExceptionCopyright © 2009-2015 MyException 版权所有