多系统间接口调用安全鉴权(App-Key、Timestamp、App-Sign)


多系统间接口调用安全鉴权(App-Key、Timestamp、App-Sign)


将secretKey发给调用系统,以备调用系统调用门户系统接口鉴权使用
 调用系统的请求头中有App-Key(调用系统名称)、Timestamp(时间戳)、App-Sign
 appSign生成规则:DigestUtils.md5Hex(appKey + timestamp + secretKey)
在收到请求后,解析请求头字段,并在本地生成appSign,
 规则:DigestUtils.md5Hex(appKey + timestamp + secretKey)
  然后比较两者是否相同,相同则放行,不同则截断

以下是鉴权工具类分享:


import cn.hutool.core.collection.CollectionUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 将secretKey发给调用系统,以备调用系统调用门户系统接口鉴权使用
 * 调用系统的请求头中有App-Key(调用系统名称)、Timestamp(时间戳)、App-Sign
 * appSign生成规则:DigestUtils.md5Hex(appKey + timestamp + secretKey)
 *
 * 在收到请求后,解析请求头字段,并在本地生成appSign,
 * 规则:DigestUtils.md5Hex(appKey + timestamp + secretKey)
 * 然后比较两者是否相同,相同则放行,不同则截断
 * @author yangqing 
 * @title: DigestUtils
 * @projectName
 * @description: 鉴权工具类
 * @date 2020/7/30 14:35
 */
public class DigestSignUtils {
    //add by yangqing 2020-07-30   start
    private static final Logger LOGGER = LoggerFactory.getLogger(DigestSignUtils.class);
    //add by yangqing 2020-07-30   end

    public static final String Timestamp = "Timestamp";

    public static final String App_Key = "App-Key";

    public static final String App_Sign = "App-Sign";

    public static Boolean isAuth(HttpServletRequest request){
        Map<String, String> headerMap = getHeadersInfo(request);
        LOGGER.info("header param is {}",headerMap);
        if(CollectionUtil.isEmpty(headerMap)) {
            return false;
        }

        //对方系统传参
        String timeStamp = MapUtils.getString(headerMap,Timestamp);
        String appKey = MapUtils.getString(headerMap,App_Key);
        String appSign = MapUtils.getString(headerMap,App_Sign);
        if(StringUtils.isEmpty(timeStamp) || StringUtils.isEmpty(appKey) || StringUtils.isEmpty(appSign)) {
            return false;
        }

        //appkey+timestamp+本地secretkey生成sign
        //从数据库中根据appKey 获取systemSecretKey  暂时写死  待写业务逻辑时修改回来
        String systemSecretKey = "0266a29fa1fa4e02a1e960f25e4ae87e";
        String realAppSign = DigestUtils.md5Hex(appKey + timeStamp + systemSecretKey);
        LOGGER.info("realAppSign is {},appSign is {}",realAppSign,appSign);
        //比对成功,则放行
        if(StringUtils.equals(appSign, realAppSign)) {
            return true;
        }
        return false;
    }

    /**
     * 获取请求头字段key-value
     *@Author yangqing 
     *@Date  2020/7/30 10:47
     *@param request
     *@return java.util.Map<java.lang.String,java.lang.String>
     *@throws
     */
    private static Map<String, String> getHeadersInfo(HttpServletRequest request) {
        //add by yangqing --获取请求头字段key-value 20200730 start
        LOGGER.info("{} : 获取请求头字段key-value  request:", request);
        Map<String, String> map = new HashMap<String, String>();
        Enumeration headerNames = request.getHeaderNames();
        //性能考虑:使用Enumeration
        /**
         *     Enumeration keys costs 6 milliseconds
         *   Enumeration elements costs 5 milliseconds
         *   Iterator keySet costs 10 milliseconds
         *   Iterator entrySet costs 10 milliseconds
         */
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        LOGGER.info("{} : 获取请求头字段key-value  获取请求头参数:", map);
        return map;
        //add by yangqing --获取请求头字段key-value 20200730 end
    }
}

以下是很挫很挫的main函数测试:


import javax.servlet.*;
import javax.servlet.http.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.*;

public class DigestSignTest {
    public static void main(String[] args) {
        HttpServletRequest request = new HttpServletRequest() {
            public String getAuthType() {
                return null;
            }

            public Cookie[] getCookies() {
                return new Cookie[0];
            }

            public long getDateHeader(String s) {
                return 0;
            }

            public String getHeader(String s) {
                Map<String, String> v = new HashMap<String, String>();
                v.put("Timestamp", "12345678912");
                v.put("App-Key", "superMan");
                v.put("App-Sign", "00d777ecfe05b9bd2a4d616f58b44556");
                return v.get(s);
            }

            public Enumeration<String> getHeaders(String s) {
                Vector v = new Vector();
                v.addElement("Timestamp");
                v.addElement("App-Key");
                v.addElement("App-Sign");
                Enumeration e = v.elements();
                return e;
            }

            public Enumeration<String> getHeaderNames() {
                Vector v = new Vector();
                v.addElement("Timestamp");
                v.addElement("App-Key");
                v.addElement("App-Sign");
                Enumeration e = v.elements();
                return e;
            }

            public int getIntHeader(String s) {
                return 0;
            }

            public String getMethod() {
                return null;
            }

            public String getPathInfo() {
                return null;
            }

            public String getPathTranslated() {
                return null;
            }

            public String getContextPath() {
                return null;
            }

            public String getQueryString() {
                return null;
            }

            public String getRemoteUser() {
                return null;
            }

            public boolean isUserInRole(String s) {
                return false;
            }

            public Principal getUserPrincipal() {
                return null;
            }

            public String getRequestedSessionId() {
                return null;
            }

            public String getRequestURI() {
                return null;
            }

            public StringBuffer getRequestURL() {
                return null;
            }

            public String getServletPath() {
                return null;
            }

            public HttpSession getSession(boolean b) {
                return null;
            }

            public HttpSession getSession() {
                return null;
            }

            public String changeSessionId() {
                return null;
            }

            public boolean isRequestedSessionIdValid() {
                return false;
            }

            public boolean isRequestedSessionIdFromCookie() {
                return false;
            }

            public boolean isRequestedSessionIdFromURL() {
                return false;
            }

            public boolean isRequestedSessionIdFromUrl() {
                return false;
            }

            public boolean authenticate(HttpServletResponse httpServletResponse) throws IOException, ServletException {
                return false;
            }

            public void login(String s, String s1) throws ServletException {

            }

            public void logout() throws ServletException {

            }

            public Collection<Part> getParts() throws IOException, ServletException {
                return null;
            }

            public Part getPart(String s) throws IOException, ServletException {
                return null;
            }

            public <T extends HttpUpgradeHandler> T upgrade(Class<T> aClass) throws IOException, ServletException {
                return null;
            }

            public Object getAttribute(String s) {
                return null;
            }

            public Enumeration<String> getAttributeNames() {
                return null;
            }

            public String getCharacterEncoding() {
                return null;
            }

            public void setCharacterEncoding(String s) throws UnsupportedEncodingException {

            }

            public int getContentLength() {
                return 0;
            }

            public long getContentLengthLong() {
                return 0;
            }

            public String getContentType() {
                return null;
            }

            public ServletInputStream getInputStream() throws IOException {
                return null;
            }

            public String getParameter(String s) {
                return null;
            }

            public Enumeration<String> getParameterNames() {
                return null;
            }

            public String[] getParameterValues(String s) {
                return new String[0];
            }

            public Map<String, String[]> getParameterMap() {
                return null;
            }

            public String getProtocol() {
                return null;
            }

            public String getScheme() {
                return null;
            }

            public String getServerName() {
                return null;
            }

            public int getServerPort() {
                return 0;
            }

            public BufferedReader getReader() throws IOException {
                return null;
            }

            public String getRemoteAddr() {
                return null;
            }

            public String getRemoteHost() {
                return null;
            }

            public void setAttribute(String s, Object o) {

            }

            public void removeAttribute(String s) {

            }

            public Locale getLocale() {
                return null;
            }

            public Enumeration<Locale> getLocales() {
                return null;
            }

            public boolean isSecure() {
                return false;
            }

            public RequestDispatcher getRequestDispatcher(String s) {
                return null;
            }

            public String getRealPath(String s) {
                return null;
            }

            public int getRemotePort() {
                return 0;
            }

            public String getLocalName() {
                return null;
            }

            public String getLocalAddr() {
                return null;
            }

            public int getLocalPort() {
                return 0;
            }

            public ServletContext getServletContext() {
                return null;
            }

            public AsyncContext startAsync() throws IllegalStateException {
                return null;
            }

            public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException {
                return null;
            }

            public boolean isAsyncStarted() {
                return false;
            }

            public boolean isAsyncSupported() {
                return false;
            }

            public AsyncContext getAsyncContext() {
                return null;
            }

            public DispatcherType getDispatcherType() {
                return null;
            }
        };
        Boolean bl = DigestSignUtils.isAuth(request);
        System.out.println("bl:" + bl);
    }
}

谢谢大家的支持,希望对大佬们有帮助!


你可能感兴趣的:(java代码及技术)