其他分享
首页 > 其他分享> > 加解密+远程请求

加解密+远程请求

作者:互联网

1,发送远程请求

public class A {
    @Value("${bizopen.url.aaoms.saveStudent}")
    private String saveStudentUrl;
    @Autowired
    private AuthValidatorProperties propAuth;
   
    public JSONObject save() {
        JSONObject json = new JSONObject();
        json.put("no","1111");
        //远程请求
        JSONObject result = this.fetchDataFromOpenServiceSuccess(saveStudentUrl, json, HttpMethod.POST);
    }

    public JSONObject fetchDataFromOpenServiceSuccess(String url, JSONObject body, HttpMethod method) {
    JSONObject result = this.exchangeWithRestTemplate(url, body, getRequestHeader(), method);
    return result;
    }
    
    punlic MultiValueMap<String, String> getRequestHeader() {
    
     MultiValueMap<String, String> header = new LinkedMultiValueMap<>();
        List<String> values = new ArrayList<>();
        String random = UUID.randomUUID().toString().replace("-", "");

        String str = PortalConstant.AUTHORIZATION_PARAM_KEY_APPID + "=" + propAuth.getAppId() + "&"
                + PortalConstant.AUTHORIZATION_PARAM_KEY_TIMESTAMP + "=" + System.currentTimeMillis() + "&"
                + PortalConstant.AUTHORIZATION_PARAM_KEY_RANDOM + "=" + random;

        String appSecret = EncryptUtil.getInstance().desDecode(propAuth.getAppSecret(), propAuth.getAppId());
        String encryStr = str + "&" + PortalConstant.AUTHORIZATION_PARAM_KEY_SIGN + "="
                + EncryptUtil.getInstance().desEncode(str, appSecret);
        String auth = PortalConstant.AUTHORIZATION_BEARER + EncryptUtil.getInstance().base64Encode(encryStr) + random;
        values.add(auth);
        header.put(PortalConstant.AUTHORIZATION, values);
        return header; 
    }
    
    public JSONObject exchangeWithRestTemplate(String url, JSONObject body, MultiValueMap<String, String> headers, HttpMethod method) {
        RestTemplate rest = new RestTemplate();
        try {
	        ResponseEntity<JSONObject> res = rest.exchange(url, method, new HttpEntity<>(body, headers), JSONObject.class);
			if (res != null) {
				return res.getBody();
			}
        } catch (RestClientException e) {
        	return "Failed to connect remote server!!!";
        }
        return null;
    }
}

 实体类AuthValidatorProperties

@Data
@ConfigurationProperties(prefix = "auth.validator")
public class AuthValidatorProperties {

    private String appId;

    private String appSecret;
}

常量类PortalConstant

public class PortalConstant {
    /** 访问接口加解密处理 */
    public final static String AUTHORIZATION_PARAM_KEY_APPID = "appId";
    public final static String AUTHORIZATION_PARAM_KEY_TIMESTAMP = "timestamp";
    public final static String AUTHORIZATION_PARAM_KEY_RANDOM = "randomStr";
    public final static String AUTHORIZATION_PARAM_KEY_SIGN = "sign";

    /* 认证 */
    public final static String AUTHORIZATION = "Authorization";
    /* 认证bearer */
    public final static String AUTHORIZATION_BEARER = "Bearer ";
}

配置文件 application.yml https://blog.csdn.net/weixin_42193908/article/details/118015425

appid 与 appSecret 有无加密都可,根据自己需要

bizopen:
  url:
    aaoms:
      base: http://localhost:8080/bizopen/aaoms
#自行配置值 
auth:
  validator:
    appId: xxxxxxxxxx
    appSecret: xxxxxxxxxxxxxxxxx

2,接收 解密 url 需要自行增加或选择不增加,代码修改即可(这里url 为远程接口地址)

定义配置类

@Configuration
public class EnableAccessConfig {
	@Value("${app.url.uiap.appInfo}")
	private String url;
	
	@Bean
	public AccessAuthorizationValidator accessAuthorizationValidator() {
		return new AccessAuthorizationValidator(url);
	}
	
	@Bean
    public FilterRegistrationBean<Filter> filterRegistrationBean(){
        FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
        bean.setFilter(new AccessAuthorizationFilter(this.accessAuthorizationValidator()));
        bean.addUrlPatterns("/*");
        return bean;
    }
	
}

过滤器

public class AccessAuthorizationFilter implements Filter {
	
	private AccessAuthorizationValidator validator; 
	
	public AccessAuthorizationFilter(AccessAuthorizationValidator validator) {
		this.validator = validator;
	}

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    	JSONObject d = validator.validate((HttpServletRequest) request);
        if (CollectionUtils.isEmpty(d)) {
            chain.doFilter(request, response);
        } else {
        	if (StringUtil.isEmpty(response.getContentType())) {
            	response.setContentType("application/json");
        	}
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.append(d.toJSONString());
            return;
        }
    }

}

解密

public class AccessAuthorizationValidator {

	private String url;
	
	public AccessAuthorizationValidator(String url) {
		this.url = url;
	}
	
    public JSONObject validate(HttpServletRequest request) {
        String authorization = request.getHeader(OpenCommonConstant.AUTHORIZATION);
        if (null == authorization || authorization.length() <= 32) {
            return this.getReturnJSONObject(30, "访问权限校验失败-参数错误", null);
        }
        //随机数
        String random = authorization.substring(authorization.length() - 32);
        //获取加密参数
        String encry = authorization.substring(7, authorization.length() - 32);
        //解密参数
        String bearerInfo = EncryptUtil.getInstance().base64Decode(encry);
        JSONObject authParam = this.getAuthParam(bearerInfo);
        String sign = authParam.getString(OpenCommonConstant.AUTHORIZATION_PARAM_KEY_SIGN);
        long timestamp = authParam.getLongValue(OpenCommonConstant.AUTHORIZATION_PARAM_KEY_TIMESTAMP);
        // 校验时间戳
        long now = new Date().getTime();
        long time = (now - timestamp) / 60000;
        if (time > 5) {
            return this.getReturnJSONObject(30, "访问权限校验失败-请求超时", null);
        }
        String appId = authParam.getString(OpenCommonConstant.AUTHORIZATION_PARAM_KEY_APPID);
        JSONObject app = this.getAppInfoFromUiapCsp(appId);
        if (app == null || StringUtil.isEmpty(app.getString(OpenCommonConstant.UIAP_DATA_KEY_APP_SECRET))) {
            return this.getReturnJSONObject(30, "访问权限校验失败-APPID错误", null);
        }
        String appSecret = app.getString(OpenCommonConstant.UIAP_DATA_KEY_APP_SECRET);
        String str = OpenCommonConstant.AUTHORIZATION_PARAM_KEY_APPID + "=" + appId 
        					+ "&" + OpenCommonConstant.AUTHORIZATION_PARAM_KEY_TIMESTAMP + "=" + timestamp 
        					+ "&" + OpenCommonConstant.AUTHORIZATION_PARAM_KEY_RANDOM + "=" + random;
        //解密str
        String s = EncryptUtil.getInstance().desDecode(sign, appSecret);
        if (!str.equals(s)) {
            return this.getReturnJSONObject(30, "访问权限校验失败-校验失败", null);
        }
        return null;
    }

    private JSONObject getAppInfoFromUiapCsp(String appId) {
    	JSONObject param = new JSONObject();
    	param.put(OpenCommonConstant.UIAP_DATA_KEY_APP_ID, appId);
    	RestTemplate rest = new RestTemplate();
        ResponseEntity<JSONObject> res = rest.exchange(this.url, HttpMethod.POST, new HttpEntity<>(param, null), JSONObject.class);
		if (res != null && res.getBody() != null) {
			return res.getBody().getJSONObject("data");
		}
        return null;
    }

    private JSONObject getReturnJSONObject(Integer errorCode, String errorMsg, Object data) {
    	JSONObject json = new JSONObject();
    	json.put("errorCode", errorCode);
    	json.put("errorMsg", errorMsg);
    	json.put("data", data);
        return json;
    }

    private JSONObject getAuthParam(String params) {
        if (params != null) {
            String[] paramArray = params.split("&");
            if (paramArray != null && paramArray.length > 0) {
            	JSONObject json = new JSONObject();
                for (String p : paramArray) {
                    String[] pv = p.split("=");
                    if (pv != null && pv.length == 2) {
                    	json.put(pv[0], pv[1]);
                    }
                }
                return json;
            }
        }
        return null;
    }

    public static void main(String[] args) {
        String authorization = "c3ff93b4-02f2-47e1-8fd5-eec30f150fb7:69428369-2dca-4fd6-9718-b3a2711dbd7a";
        System.out.println(EncryptUtil.getInstance().base64Encode(authorization));
    }

}

常量类

public class OpenCommonConstant {

    /**
     * 认证参数KEY
     */
    public final static String AUTHORIZATION_PARAM_KEY_APPID = "appId";
    public final static String AUTHORIZATION_PARAM_KEY_TIMESTAMP = "timestamp";
    public final static String AUTHORIZATION_PARAM_KEY_RANDOM = "randomStr";
    public final static String AUTHORIZATION_PARAM_KEY_SIGN = "sign";
    
    public final static String UIAP_DATA_KEY_APP_ID = "appId";
    public final static String UIAP_DATA_KEY_APP_SECRET = "appSecret";

    /* 认证 */
    public final static String AUTHORIZATION = "Authorization";
    /* 认证bearer */
    public final static String AUTHORIZATION_BEARER = "Bearer ";
    /* 请求内容 */
    public final static String CONTENT_TYPE = "Content-Type";
    /* 请求内容类型 */
    public final static String CONTENT_TYPE_VALUE = "application/json;charset=UTF-8";



}

3,衍生 springboot 注解模式,在使用的地方添加注解@EnableAccessFilter(一般在启动类加)

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import({ EnableAccessConfig.class })
public @interface EnableAccessFilter {

}

标签:return,String,JSONObject,加解密,远程,KEY,public,AUTHORIZATION,请求
来源: https://blog.csdn.net/weixin_42193908/article/details/122804500