自定义拦截器拦截Http请求,校验handler中的密钥

一、自定义注解

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 请求拦截,校验header中秘钥
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CheckSecretkeyRequired {
}

二、被拦截的接口

 /**
     * 查询
     * @param map
     * @return
     */
    @CheckSecretkeyRequired
    @PostMapping("/getAll")
    public Result getAll(@RequestParam Map<String, Object> map){
         return Result.success(Arrays.asList());
    }

三、拦截器

import com.cloud.industryapi.config.annotion.CheckSecretkeyRequired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

public class SourceAccessInterceptor implements HandlerInterceptor {

    @Value("${secret.key}")
    private String secretKey;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        CheckSecretkeyRequired loginRequired = handlerMethod.getMethod().getAnnotation(CheckSecretkeyRequired.class);
        if(loginRequired == null){
            return true;
        }
        String requestSecretKey = request.getHeader("secretKey");
        if(secretKey.equals(requestSecretKey)) {
            return true;
        }else {
            response.setContentType("application/json; charset=utf-8");
            response.getWriter().print("你访问的资源秘钥不正确!");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

四、Http请求工具类

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@SuppressWarnings("all")
public class HttpsUtils {

	public static String Method_GET = "GET";
	public static String Method_POST = "POST";
	public static String Method_PUT = "PUT";
	public static String Method_DELETE = "DELETE";

    /**
     * Send SSL Request (发送请求带秘钥)(不包含get请求)
     * @param reqURL
     * @param str
     * @param Secretkey 约定的秘钥,存Header里
     * @return
     * @throws IOException
     * @throws KeyStoreException
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */

    public static String sendSSLRequestIncludeSecretkey(String reqURL, Map<String, Object> params, String method, String Secretkey) {

        String responseContent = null;
        CloseableHttpClient client = null;
        try {
            List<NameValuePair> nameValuePairs = new ArrayList <NameValuePair>();
            if(params != null && params.size() > 0){
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
                }
            }
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
            SSLContext sslContext = SSLContexts.custom()
                    .loadTrustMaterial(null, new TrustStrategy() {
                        @Override
                        public boolean isTrusted(
                                X509Certificate[] x509Certificates, String s)
                                throws CertificateException {
                            return true;
                        }
                    }).build();
            //创建httpClient
            client = HttpClients.custom().setSslcontext(sslContext).
                    setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
            HttpResponse response = null;
            if (method.equals(Method_POST)) {
                HttpPost httpPost = new HttpPost(reqURL);
                httpPost.setEntity(formEntity);
                httpPost.setHeader("dlhSecretkey",Secretkey);
                response = client.execute(httpPost);
            } else if (method.equals(Method_PUT)) {
                HttpPut httpPut = new HttpPut(reqURL);
                httpPut.setEntity(formEntity);
                httpPut.setHeader("dlhSecretkey",Secretkey);
                response = client.execute(httpPut);
            } else if (method.equals(Method_DELETE)) {
                HttpDelete httpDelete = new HttpDelete(reqURL);
                httpDelete.setHeader("dlhSecretkey",Secretkey);
                response = client.execute(httpDelete);
            }

            HttpEntity entity = response.getEntity();

            if (null != entity) {
                responseContent = EntityUtils.toString(entity, "UTF-8");
                EntityUtils.consume(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(client != null){
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return responseContent;
    }

    public static void main(String[] args) {
        Map<String, Object> paramMap = new HashMap<>();
        String secretKey = "secretKey";
        String url = "url";
        String response = HttpsUtils.sendSSLRequestIncludeSecretkey(url, paramMap, HttpsUtils.Method_POST, secretKey);
        if (StringUtils.isNotEmpty(response)) {
            Map<String, Object> returnMap = JSONObject.parseObject(response, new TypeReference<Map<String, Object>>() {});
            String data = returnMap.get("data").toString();
            List<entity> factoryDemoList = JSONObject.parseArray(data, entity.class);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值