Java SDK使用说明
操作场景
使用Java语言进行后端服务签名时,您需要先获取SDK,然后导入工程,最后参考校验后端签名示例校验签名是否一致。
Java SDK仅支持hmac和basic类型的后端服务签名。
前提条件
- 已ROMA Connect控制台创建签名密钥,并绑定API,具体请参见配置后端服务的签名校验。
- 已获取签名密钥的Key和Secret,具体请参见开发准备。
- 已安装开发工具和Java开发语言环境,具体请参见开发准备。
获取SDK
旧版界面:登录ROMA Connect实例控制台,在“服务集成 APIC > API管理”的“签名密钥”页签中下载SDK。
新版界面:登录ROMA Connect实例控制台,在“服务集成 APIC > 凭据管理”的“SDKs”页签中下载SDK。
导入工程
- 打开IntelliJ IDEA,在菜单栏选择“File > New > Project from Existing Sources”,选择解压后的“apigateway-backend-signature-demo\pom.xml”文件,单击“OK”。
图1 Select File or Directory to Import
- 保持默认设置,单击“Next > Next > Next > Next > Finish”,完成工程导入。
- 在右侧Maven页签,双击“compile”进行编译。
图2 编译工程
返回“BUILD SUCCESS”,表示编译成功。
- 右键单击BackendSignatureApplication,选择“Run”运行服务。
图3 运行服务
“ApigatewaySignatureFilter.java”为示例代码,请根据实际情况修改参数后使用。具体代码说明请参考校验hmac类型后端签名示例。
校验hmac类型后端签名示例
- 示例演示如何编写一个基于Spring boot的服务器,作为API的后端,并且实现一个Filter,对APIC的请求做签名校验。
- API绑定hmac类型签名密钥后,发给后端的请求中会添加签名信息。
- 编写一个Controller,路径为/hmac。
// HelloController.java @RestController @EnableAutoConfiguration public class HelloController { @RequestMapping("/hmac") private String hmac() { return "Hmac authorization success"; } }
- 编写一个Filter,匹配所有路径和方法。将允许的签名key和secret对放入一个Map中。
public class ApigatewaySignatureFilter implements Filter { private static Map<String, String> secrets = new HashMap<>(); static { // Directly writing AK/SK in code is risky. For security, encrypt your AK/SK and store them in the configuration file or environment variables. // In this example, the AK/SK are stored in environment variables for identity authentication. Before running this example, set environment variables HUAWEICLOUD_SDK_AK1, HUAWEICLOUD_SDK_SK1, and HUAWEICLOUD_SDK_AK2, HUAWEICLOUD_SDK_SK2. secrets.put(System.getenv("HUAWEICLOUD_SDK_AK1"), System.getenv("HUAWEICLOUD_SDK_SK1")); secrets.put(System.getenv("HUAWEICLOUD_SDK_AK2"), System.getenv("HUAWEICLOUD_SDK_SK2")); } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) { //签名校验代码 ... } }
- doFilter函数为签名校验代码。校验流程如下:由于filter中需要读取body,为了使得body可以在后续的filter和controller中再次读取,把request包装起来传给后续的filter和controller。包装类的具体实现可见RequestWrapper.java。
RequestWrapper request = new RequestWrapper((HttpServletRequest) servletRequest);
- 使用正则表达式解析Authorization头,得到signingKey和signedHeaders。
private static final Pattern authorizationPattern = Pattern.compile("SDK-HMAC-SHA256\\s+Access=([^,]+),\\s?SignedHeaders=([^,]+),\\s?Signature=(\\w+)"); ... String authorization = request.getHeader("Authorization"); if (authorization == null || authorization.length() == 0) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization not found."); return; } Matcher m = authorizationPattern.matcher(authorization); if (!m.find()) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization format incorrect."); return; } String signingKey = m.group(1); String signingSecret = secrets.get(signingKey); if (signingSecret == null) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Signing key not found."); return; } String[] signedHeaders = m.group(2).split(";");
例如,Authorization头为:
SDK-HMAC-SHA256 Access=signature_key1, SignedHeaders=host;x-sdk-date, Signature=e11adf65a20d1b82c25419b5********8d0ba12fed1ceb13ed00
则解析的结果为:
signingKey=signature_key1 signedHeaders=host;x-sdk-date
- 通过signingKey找到signingSecret,如果不存在signingKey,则返回认证失败。
String signingSecret = secrets.get(signingKey); if (signingSecret == null) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Signing key not found."); return; }
- 新建一个Request对象,将请求method、url、query、signedHeaders对应的请求头放入其中。判断是否需要设置body并设置。
需要读取body的条件为:不存在值为UNSIGNED-PAYLOAD的x-sdk-content-sha256头。
Request apiRequest = new DefaultRequest(); apiRequest.setHttpMethod(HttpMethodName.valueOf(request.getMethod())); String url = request.getRequestURL().toString(); String queryString = request.getQueryString(); try { apiRequest.setEndpoint((new URL(url)).toURI()); Map<String, String> parametersmap = new HashMap<>(); if (null != queryString && !"".equals(queryString)) { String[] parameterarray = queryString.split("&"); for (String p : parameterarray) { String[] p_split = p.split("=", 2); String key = p_split[0]; String value = ""; if (p_split.length >= 2) { value = p_split[1]; } parametersmap.put(URLDecoder.decode(key, "UTF-8"), URLDecoder.decode(value, "UTF-8")); } apiRequest.setParameters(parametersmap); //set query } } catch (URISyntaxException e) { e.printStackTrace(); } boolean needbody = true; String dateHeader = null; for (int i = 0; i < signedHeaders.length; i++) { String headerValue = request.getHeader(signedHeaders[i]); if (headerValue == null || headerValue.length() == 0) { ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED, "signed header" + signedHeaders[i] + " not found."); } else { apiRequest.addHeader(signedHeaders[i], headerValue);//set header if (signedHeaders[i].toLowerCase().equals("x-sdk-content-sha256") && headerValue.equals("UNSIGNED-PAYLOAD")) { needbody = false; } if (signedHeaders[i].toLowerCase().equals("x-sdk-date")) { dateHeader = headerValue; } } } if (needbody) { apiRequest.setContent(new ByteArrayInputStream(request.getBody())); //set body }
- 校验签名是否过期。从X-Sdk-Date头中取出时间,判断与服务器时间是否相差在15分钟以内。如果signedHeaders中不包含X-Sdk-Date,也返回认证失败。
private static final DateTimeFormatter timeFormatter = DateTimeFormat.forPattern("yyyyMMdd'T'HHmmss'Z'").withZoneUTC(); ... if (dateHeader == null) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Header x-sdk-date not found."); return; } long date = timeFormatter.parseMillis(dateHeader); long duration = Math.abs(DateTime.now().getMillis() - date); if (duration > 15 * 60 * 1000) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Signature expired."); return; }
- 将Authorization头也放入Request对象中,调用verify方法校验请求签名。如果校验通过,则执行下一个filter,否则返回认证失败。
DefaultSigner signer = (DefaultSigner) SignerFactory.getSigner(); boolean verify = signer.verify(apiRequest, new BasicCredentials(signingKey, signingSecret)); if (verify) { chain.doFilter(request, response); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "verify authroization failed."); }
- 注册filter和路径的映射关系。
@Configuration public class FilterConfig { @Bean public FilterRegistrationBean registApigatewaySignatureFilter() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new ApigatewaySignatureFilter()); registration.addUrlPatterns("/hmac"); registration.setName("ApigatewaySignatureFilter"); return registration; } }
- 运行服务器,验证代码正确性。下面示例使用JavaScript SDK中的html签名工具生成签名。
填入如图所示字段后,单击“Send request”,复制生成的curl命令,并在命令行中执行,服务器返回“Hello World!”。
如果使用错误的Key和Secret访问,服务器返回401认证不通过。
校验basic类型后端签名示例
- 示例演示如何编写一个基于Spring boot的服务器,作为API的后端,并且实现一个Filter,对APIC的请求做签名校验。
- API绑定basic类型签名密钥后,发给后端的请求中会添加basic认证信息,其中basic认证的用户名为签名密钥的key,密码为签名密钥的secret。
- 编写一个Controller,路径为/basic。
// HelloController.java @RestController @EnableAutoConfiguration public class HelloController { @RequestMapping("/basic") private String basic() { return "Basic authorization success"; } }
- 编写一个Filter,按照basic认证的规则,Authorization头格式为"Basic "+base64encode(username+":"+password)。以下为根据规则编写的校验代码。
// BasicAuthFilter.java public class BasicAuthFilter implements Filter { private static final String CREDENTIALS_PREFIX = "Basic "; private static Map<String, String> secrets = new HashMap<>(); static { secrets.put("signature_key1", "signature_secret1"); secrets.put("signature_key2", "signature_secret2"); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; try { String credentials = request.getHeader("Authorization"); if (credentials == null || credentials.length() == 0) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization not found."); return; } if (!credentials.startsWith(CREDENTIALS_PREFIX)) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization format incorrect."); return; } String authInfo = credentials.substring(CREDENTIALS_PREFIX.length()); String decoded; try { decoded = new String(Base64.getDecoder().decode(authInfo)); } catch (IllegalArgumentException e) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization format incorrect."); return; } String[] spl = decoded.split(":", 2); if (spl.length < 2) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization format incorrect."); return; } String signingSecret = secrets.get(spl[0]); if (signingSecret == null) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Username not found."); return; } if (signingSecret.equals(spl[1])) { chain.doFilter(request, response); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Incorrect username or password"); } } catch (Exception e) { e.printStackTrace(); try { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (IOException e1) { } } } }
- 注册filter和路径的映射关系。
@Configuration public class FilterConfig { @Bean public FilterRegistrationBean registBasicAuthFilter() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new BasicAuthFilter()); registration.addUrlPatterns("/basic"); registration.setName("BasicAuthFilter"); return registration; } }
- 运行服务器,验证代码正确性。将用户名和密码生成basic认证的Authorization头域传给请求接口。如果使用错误的用户名和密码访问,服务器返回401认证不通过。