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 roleList = new ArrayList();
      List permissionList = new ArrayList();
      String userName = shiroUser.getUsername();
//    if(StringUtils.equals("20160606", userName)) {
List 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 = 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 branchArr = this.baseService.queryForJDBCList(sql);
            if (null != branchArr&& branchArr.size() > 0) {
                 for (Iterator it = branchArr.iterator(); it.hasNext();) {//遍历角色菜单
Map resource = it.next();
                         if (!"".equals(resource)&&resource!=null) {
                           permissionList.add(resource.get("URL")+"");
                        }
                 }
            }
         }
         }
         
      }
         SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
         
         //这个确定页面?标签的name的??
//       roleList.add("admin");
info.addRoles(roleList);
         //这个就是页面?  标签的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;
      }

      /**
       * 本函数输出将作为默认?输出.
       */
@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;
   }
   
}

 

 

 

 

 

 

 

你可能感兴趣的:(shiro)