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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM