Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: Hmac-auth plugin call example supports Java language #11929

Open
fanchangjifen opened this issue Jan 21, 2025 · 2 comments
Open

docs: Hmac-auth plugin call example supports Java language #11929

fanchangjifen opened this issue Jan 21, 2025 · 2 comments
Labels
doc Documentation things enhancement New feature or request

Comments

@fanchangjifen
Copy link

Current State

https://apisix.apache.org/zh/docs/apisix/plugins/hmac-auth/

Desired State

The authentication process of the hmac-auth plugin based on draft-capage-http-signatures is quite complex, and currently only the Python version is provided by the official. We hope to provide Java call examples to illustrate

@fanchangjifen fanchangjifen added the doc Documentation things label Jan 21, 2025
@dosubot dosubot bot added the enhancement New feature or request label Jan 21, 2025
@fanchangjifen
Copy link
Author

Java示例(以Hmac-sha256算法实现为例)

部分写法可能不是最优的方案,仅供参考.

Date需要按照格林尼治时间进行格式化.

Authorization部分需要注意空格和换行符.

import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.HmacAlgorithms;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.bouncycastle.util.encoders.Hex;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.Security;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Locale;

public class Test {

    private static final String keyId = "111111111111111";

    private static final String secretKey = "222222222222222";

    private static final String algorithm = "hmac-sha256";

    public static void main(String[] args) throws IOException {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        String uri = "/uri";
        HttpGet httpGet = new HttpGet("http://127.0.0.1:9080" + uri);

        String requestDate = dateTimeMillis2GMTString(new Date().getTime(),"EEE, d MMM yyyy HH:mm:ss 'GMT'");
        StringBuilder signature = new StringBuilder()
                .append(keyId).append("\n")
                .append(HttpGet.METHOD_NAME).append(" ").append(uri).append("\n")
                //注意date后面空格
                .append("date:").append(" ").append(requestDate).append("\n");
        String xHmacSignature = hmacSha256Base64Str(secretKey, signature.toString());
        StringBuilder authorization = new StringBuilder()
                .append("Signature").append(" ").append("keyId=").append('\"').append(keyId).append('\"').append(",algorithm=").append('\"').append(algorithm).append('\"').append(",")
                .append("headers=").append('\"').append("@request-target date").append('\"').append(",")
                .append("signature=").append('\"').append(xHmacSignature).append('\"');
        httpGet.setHeader("Date", requestDate.toString());
        httpGet.setHeader("Authorization",authorization.toString());
        System.out.println(JSONObject.toJSONString(httpGet));
        HttpResponse response = httpClient.execute(httpGet);
        System.out.println("请求响应状态" + response.getStatusLine().getStatusCode());
        String responseStr = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
        System.out.println(responseStr);
    }

    public static String hmacSha256Base64Str(final String key, final String data) {
        try {
            final Mac mac = Mac.getInstance(HmacAlgorithms.HMAC_SHA_256.toString());
            final SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), mac.getAlgorithm());
            mac.init(signingKey);
            byte[] hmacShaBytes = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
            return new String(Base64.encodeBase64(hmacShaBytes), StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String dateTimeMillis2GMTString(long time,String format){
        Instant instant = Instant.ofEpochMilli(time);
        ZoneId zone = ZoneId.of("GMT");
        return LocalDateTime.ofInstant(instant, zone).format(DateTimeFormatter.ofPattern(format, Locale.ENGLISH));
    }
}

@fanchangjifen
Copy link
Author

apisix-website这个项目我本地编译有问题,无法启动,以上是我本地测试的java示例,有需要的可参考

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
doc Documentation things enhancement New feature or request
Projects
Status: 📋 Backlog
Development

No branches or pull requests

1 participant