# 实现基本认证

使用基本认证时,参数如下表所示:

参数名称

类型

必选

描述

X-Jcc-Authorization

String

HTTP 身份认证头部字段,凭证信息生成方式在实现方法中说明。

# 实现方法

  • 获取客户鉴权密钥,具体请参见通过控制台使用短信服务中的获取鉴权密钥步骤。

  • 通过Account ID , API Key,和API Secret,生成一个使用 Base64 算法编码的凭证,并在 HTTP 请求头部的 X-Jcc-Authorization 字段中填入该凭证。凭证格式为: <API Key>:<API Secret>。

# 示例代码

下列示例代码实现了 HTTP 基本认证:

  • JAVA 示例代码采用Spring Boot框架自带的RestTemplate,如果采用其他HTTP框架请自行支持POST重定向。
    1. 支持POST的重定向
 package com.juphoon.rcs.controller;

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;

@Configuration
public class RestTemplateConfig {

   @Bean("laxRestTemplate")
   public RestTemplate laxRestTemplate() {
      HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
      httpRequestFactory.setConnectionRequestTimeout(2000);
      httpRequestFactory.setConnectTimeout(10000);
      httpRequestFactory.setReadTimeout(72000);
      HttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
      httpRequestFactory.setHttpClient(httpClient);
      RestTemplate restTemplate = new RestTemplate(httpRequestFactory);
      return restTemplate;
   }

}
  1. 关键代码逻辑
package com.juphoon.rcs.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.Base64;

@RequestMapping("/test")
@RestController
public class TestController {
    @Autowired
    private RestTemplate laxRestTemplate;

    @GetMapping("/basic")
    public void basicAuth() {

        // 客户 API Key
        final String customerAPIKey = "Your customer api key";
        // 客户 API Secret
        final String customerAPISecret = "Your customer api secret";

        // 拼接客户 ID 和客户鉴权信息并使用 base64 编码
        String plainCredentials =  customerAPIKey + ":" + customerAPISecret;
        String base64Credentials = new String(Base64.getEncoder().encode(plainCredentials.getBytes()));
        // 创建 authorization header
        String authorizationHeader = "Basic " + base64Credentials;

        String urlString = "https://sms.api.juphoon.com/sms/v1";
        String content = "Your Send Payload Json String";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("X-Jcc-Authorization", authorizationHeader);
        HttpEntity requestEntity = new HttpEntity<>(content, headers);
        ResponseEntity<String> response = laxRestTemplate.exchange(urlString, HttpMethod.POST, requestEntity, String.class);
    }
  • Golang
package main

import (
    "encoding/base64"
    "fmt"
    "io/ioutil"
    "net/http"
    "strings"
)

const (
    // 客户 API Key
    customerAPIKey = "Your customer key"
    // 客户 API Secret
    customerAPISecret = "Your customer secret"
)

// Basic 认证实现
func main() {
    client := &http.Client{}
    req, err := http.NewRequest(
        "POST",
        "https://sms.api.juphoon.com/sms/v1",
        strings.NewReader("Your Send Payload Json String"))
    if err != nil {
        fmt.Println(err)
        return
    }

    // 拼接客户 ID 和客户鉴权信息并使用 base64 编码
    plainCredentials := customerAPIKey + ":" + customerAPISecret
    base64Credentials := base64.StdEncoding.EncodeToString([]byte(plainCredentials))

    // 增加 Authorization header
    req.Header.Add("X-Jcc-Authorization", "Basic "+base64Credentials)
    req.Header.Add("Content-Type", "application/json")

    // 发送 HTTP 请求
    res, err := client.Do(req)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer res.Body.Close()

    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(body))
}
最后更新时间: 2022/4/22 09:23:40