梦相随1006

版权归 梦相随1006 所有,未经 https://www.cnblogs.com/xin1006 作者许可,严禁转载

导航

SpringSecurity 登录 - 以及Md5加密

 

我们现在开放一个链接给其他系统,来访问我们的系统

 

http://localhost:8080/hulk-teller-web/haihui!init.jspa?loginId=teller01&key=SD33OH45O3HJ21O34N34O5

这样的方式登录.

1)按照约定的规则生成key

package hulk.frame.haihui.service;

import hulk.frame.haihui.entity.HaiHuiLogin;
import hulk.frame.haihui.support.Base32;
import hulk.frame.user.service.UserService;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("haihuiService")
public class HaiHuiServiceImpl  implements HaiHuiService  {
    
    private final static Logger logger = LogManager.getLogger(HaiHuiServiceImpl.class);
    
//    @Autowired
//    private PermissionService permissionService;
    @Autowired
    private UserService userService;
    @Override
    public boolean checkHaiHuiLogin(HaiHuiLogin loginUser) {
        // TODO Auto-generated method stub
        if(loginUser!=null){
            // 
            Integer userId=userService.getUserIdByLoginId(loginUser.getLoginId());
            if(userId!=null){
                // 将用户名设置到海辉用户登录对象中
                loginUser.setLoginName(userService.getUserNameByUserId(userId));
                // 我们平台生成的Key
                String mykey=this.generateKey(loginUser);
                if(mykey.equals(loginUser.getKey())){
                    return true;
                }
            }
        }
        
        return false;
    }
    
    
    private String generateKey(HaiHuiLogin loginUser) {
        //规则第一步:   loginId  + loginName + date 生成
        String dateStr=new SimpleDateFormat("yyyyMMddHHmm").format(new Date());
        dateStr=dateStr.substring(0, dateStr.length()-1);
        String sSource=loginUser.getLoginId()+loginUser.getLoginName()+dateStr;
        // 规则第二步:字符串反转
        StringBuffer sb=new StringBuffer(sSource);
        sSource=sb.reverse().toString();
        
        // 规则第三步:Md5加密
//        Md5PasswordEncoder passwordEncoder = new Md5PasswordEncoder();
//        return passwordEncoder.encodePassword(sSource, null);
        try {
            MessageDigest md= MessageDigest.getInstance("MD5");
            md.update(sSource.getBytes("UTF-8"));
            
            String digest = Base32.encode(md.digest());
            return digest;
        } catch (NoSuchAlgorithmException e) {
            logger.error(e.getMessage(), e);
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(), e);
        }
        
        return null;
        
    }
    
}

 

2)  自定义的Base32

package hulk.frame.haihui.support;

public class Base32 {

        private static final String base32Chars = 
                 "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; 
         private static final int[] base32Lookup = { 
             0xFF, 0xFF, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, // '0', '1', '2', '3', '4', '5', '6', '7' 
             0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // '8', '9', ':', ';', '<', '=', '>', '?' 
             0xFF, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, // '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G' 
             0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, // 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O' 
             0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, // 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W' 
             0x17, 0x18, 0x19, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 'X', 'Y', 'Z', '[', '\', ']', '^', '_' 
             0xFF, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, // '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g' 
             0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, // 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o' 
             0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, // 'p', 'q', 'r', 's', 't', 'u', 'v', 'w' 
             0x17, 0x18, 0x19, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF // 'x', 'y', 'z', '{', '|', '}', '~', 'DEL' 
         }; 

        public static String encode( 
                 final byte[] bytes) { 
             int i = 0, index = 0, digit = 0; 
             int currByte, nextByte; 
             StringBuffer base32 = new StringBuffer((bytes.length + 7) * 8 / 5); 

            while (i < bytes.length) { 
                 currByte = (bytes[i] >= 0) ? bytes[i] : (bytes[i] + 256); // unsign 

                /* Is the current digit going to span a byte boundary? */ 
                 if (index > 3) { 
                     if ((i + 1) < bytes.length) { 
                         nextByte = (bytes[i + 1] >= 0) ? bytes[i + 1] : (bytes[i + 1] + 256); 
                     } else { 
                         nextByte = 0; 
                     } 

                    digit = currByte & (0xFF >> index); 
                     index = (index + 5) % 8; 
                     digit <<= index; 
                     digit |= nextByte >> (8 - index); 
                     i++; 
                 } else { 
                     digit = (currByte >> (8 - (index + 5))) & 0x1F; 
                     index = (index + 5) % 8; 
                     if (index == 0) { 
                         i++; 
                     } 
                 } 
                 base32.append(base32Chars.charAt(digit)); 
             } 

            return base32.toString(); 
         } 

        public static byte[] decode( 
                 final String base32) { 
             int i, index, lookup, offset, digit; 
             byte[] bytes = new byte[base32.length() * 5 / 8]; 

            for (i = 0, index = 0, offset = 0; i < base32.length(); i++) { 
                 lookup = base32.charAt(i) - '0'; 

                /* Skip chars outside the lookup table */ 
                 if (lookup < 0 || lookup >= base32Lookup.length) { 
                     continue; 
                 } 

                digit = base32Lookup[lookup]; 

                /* If this digit is not in the table, ignore it */ 
                 if (digit == 0xFF) { 
                     continue; 
                 } 

                if (index <= 3) { 
                     index = (index + 5) % 8; 
                     if (index == 0) { 
                         bytes[offset] |= digit; 
                         offset++; 
                         if (offset >= bytes.length) { 
                             break; 
                         } 
                     } else { 
                         bytes[offset] |= digit << (8 - index); 
                     } 
                 } else { 
                     index = (index + 5) % 8; 
                     bytes[offset] |= (digit >>> index); 
                     offset++; 

                    if (offset >= bytes.length) { 
                         break; 
                     } 
                     bytes[offset] |= digit << (8 - index); 
                 } 
             } 
             return bytes; 
         } 
    } 

 

3) 我们的框架是ssh的, 系统使用的安全模式是   SpringSecurity

package hulk.frame.haihui.action;

import hulk.frame.action.BaseActionSupport;
import hulk.frame.haihui.entity.HaiHuiLogin;
import hulk.frame.haihui.service.HaiHuiService;
import hulk.frame.security.CurrentUser;
import hulk.frame.security.SecurityManagerSupport;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;

@Controller("haihuiAction")
public class HaiHuiAction extends BaseActionSupport {

    private static final long serialVersionUID = 1L;
    @Autowired
    private SecurityManagerSupport securityManager;
    @Autowired
    protected HaiHuiService haihuiService;
    
    public String init() {
        
        String loginId=request.getParameter("loginId");
        String key=request.getParameter("key");
        
        boolean ret=haihuiService.checkHaiHuiLogin(new HaiHuiLogin(loginId,key));
        
        if(ret){
            // 处理当前用户
            CurrentUser currUser=(CurrentUser)securityManager.loadUserByUsername(loginId);
            Authentication auth = new UsernamePasswordAuthenticationToken(currUser,loginId);
            SecurityContextHolder.getContext().setAuthentication(auth);
            
            HttpSession session = request.getSession();
            session.setAttribute("SPRING_SECURITY_CONTEXT", SecurityContextHolder.getContext()); // 这个非常重要,否则验证后将无法登陆
              
             return SUCCESS;
        }else{
            return ERROR;
        }
       
    }
    
}

4)  忽略该链接的请求

......
    <http pattern="/haihui!init.jspa" security="none"/>
......
    

5)  struts2 的配置

    <action name="auto" class="autoAction">
            <result name="success">/ext/auto/app.jsp</result>
            <result name="teller">/teller/teller_${pageName}.jsp</result>
        </action>
        
        <!-- 海辉登录系统 -->
        <action name="haihui" class="haihuiAction">
            <result name="success">/ext/auto/app.jsp</result>
        </action>

 

posted on 2015-04-22 21:10  梦相随1006  阅读(10646)  评论(0编辑  收藏  举报