Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion line-bot-api-client/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,15 @@ dependencies {
integrationTestImplementation 'com.google.guava:guava'
integrationTestImplementation 'io.jsonwebtoken:jjwt-api'
integrationTestImplementation 'io.jsonwebtoken:jjwt-jackson'
// https://github.com/jwtk/jjwt/issues/236 jjwt doens't support JWK parsing, yet.
// Once jjwt support JWK, we can remove this dependency.
integrationTestImplementation 'com.nimbusds:nimbus-jose-jwt:9.4'
integrationTestImplementation 'org.springframework.boot:spring-boot-starter-test'
integrationTestImplementation 'org.springframework.boot:spring-boot-starter-logging'
integrationTestImplementation 'com.fasterxml.jackson.core:jackson-core'
integrationTestImplementation 'com.fasterxml.jackson.core:jackson-databind'
integrationTestImplementation 'com.fasterxml.jackson.core:jackson-annotations'
integrationTestImplementation 'com.fasterxml.jackson.module:jackson-module-parameter-names'
integrationTestImplementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-yaml'
integrationTestRuntime 'io.jsonwebtoken:jjwt-impl'
integrationTestRuntimeOnly 'io.jsonwebtoken:jjwt-impl'
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.text.ParseException;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
Expand All @@ -36,8 +37,9 @@

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.BaseEncoding;
import com.nimbusds.jose.jwk.JWK;

import com.linecorp.bot.model.oauth.ChannelAccessTokenKeyIdsResponse;
import com.linecorp.bot.model.oauth.IssueChannelAccessTokenResponse;

import io.jsonwebtoken.Jwts;
Expand All @@ -51,13 +53,13 @@ public class LineOAuthClientIntegrationTest {

private LineOAuthClient target;
private String endpoint;
private String pemPrivateKey;
private JWK jwk;
private String channelId;
private String channelSecret;
private String kid;

@Before
public void setUp() throws IOException {
public void setUp() throws IOException, ParseException {
assumeThat(TEST_RESOURCE)
.isNotNull();

Expand All @@ -70,8 +72,14 @@ public void setUp() throws IOException {
.apiEndPoint(URI.create(endpoint))
.build();

pemPrivateKey = ((String) map.get("pemPrivateKey")).replaceAll("\n", "");
kid = (String) map.get("kid");
// 1. Issue new "Assertion Signing Key" in the LINE Developer Center.
// 2. You get the private key of your new assertion signing key in JWK format.
jwk = JWK.parse((String) map.get("jwk"));

kid = jwk.getKeyID();
assumeThat(kid).describedAs("kid must not be null")
.isNotNull();

channelId = String.valueOf(map.get("channelId"));
channelSecret = (String) map.get("channelSecret");
}
Expand All @@ -97,13 +105,13 @@ public void gwtTokenIntegrationTest() throws Exception {
"token_exp", Duration.ofMinutes(1).getSeconds()
);

byte[] bytes = BaseEncoding.base64().decode(pemPrivateKey);
byte[] rsaPrivateKey = jwk.toRSAKey().toRSAPrivateKey().getEncoded();

KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(bytes));
PrivateKey privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(rsaPrivateKey));

String jws = Jwts.builder()
.serializeToJsonWith(new JacksonSerializer(new ObjectMapper()))
.serializeToJsonWith(new JacksonSerializer<>(new ObjectMapper()))
.setHeader(header)
.setClaims(body)
.signWith(privateKey, SignatureAlgorithm.RS256)
Expand All @@ -117,6 +125,12 @@ public void gwtTokenIntegrationTest() throws Exception {

log.info("{}", issueChannelAccessTokenResponse);
assertThat(issueChannelAccessTokenResponse.getExpiresInSecs()).isEqualTo(60);
assertThat(issueChannelAccessTokenResponse.getKeyId()).isNotBlank();

ChannelAccessTokenKeyIdsResponse keyIdsResponse =
target.getsAllValidChannelAccessTokenKeyIdsByJWT(jws).get();
assertThat(keyIdsResponse.getKids().size()).isGreaterThan(0);
log.info("{}", keyIdsResponse);

// Revoke
target.revokeChannelTokenByJWT(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import java.util.concurrent.CompletableFuture;

import com.linecorp.bot.model.oauth.ChannelAccessTokenException;
import com.linecorp.bot.model.oauth.ChannelAccessTokenKeyIdsResponse;
import com.linecorp.bot.model.oauth.IssueChannelAccessTokenRequest;
import com.linecorp.bot.model.oauth.IssueChannelAccessTokenResponse;

Expand All @@ -35,6 +36,15 @@ static LineOAuthClientBuilder builder() {
return new LineOAuthClientBuilder();
}

/**
* Gets all valid channel access token key IDs.
* @param jwt A JSON Web Token (JWT) (opens new window)the client needs to create and sign with the private
* key.
* @return <a href="https://developers.line.biz/en/reference/messaging-api/#get-all-valid-channel-access-token-key-ids-v2-1">Get all valid channel access token key IDs v2.1</a>
*/
CompletableFuture<ChannelAccessTokenKeyIdsResponse> getsAllValidChannelAccessTokenKeyIdsByJWT(
String jwt);

/**
* Issues a channel access token. This method lets you use JWT assertion for authentication.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import com.fasterxml.jackson.databind.ObjectMapper;

import com.linecorp.bot.model.oauth.ChannelAccessTokenException;
import com.linecorp.bot.model.oauth.ChannelAccessTokenKeyIdsResponse;
import com.linecorp.bot.model.oauth.IssueChannelAccessTokenRequest;
import com.linecorp.bot.model.oauth.IssueChannelAccessTokenResponse;
import com.linecorp.bot.model.objectmapper.ModelObjectMapper;
Expand All @@ -42,6 +43,14 @@ class LineOAuthClientImpl implements LineOAuthClient {

private final LineOAuthService service;

@Override
public CompletableFuture<ChannelAccessTokenKeyIdsResponse> getsAllValidChannelAccessTokenKeyIdsByJWT(
String jwt) {
return toFuture(service.getsAllValidChannelAccessTokenKeyIds(
"urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
jwt));
}

@Override
public CompletableFuture<IssueChannelAccessTokenResponse> issueChannelTokenByJWT(final String jwt) {
return toFuture(service.issueChannelTokenByJWT(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,16 @@
import java.util.concurrent.CompletableFuture;

import com.linecorp.bot.model.oauth.ChannelAccessTokenException;
import com.linecorp.bot.model.oauth.ChannelAccessTokenKeyIdsResponse;
import com.linecorp.bot.model.oauth.IssueChannelAccessTokenResponse;

import lombok.experimental.PackagePrivate;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;

/**
* An OAuth client that issues or revokes channel access tokens. See {@link LineOAuthClient} and
Expand All @@ -34,6 +37,14 @@
*/
@PackagePrivate
interface LineOAuthService {
/**
* Gets all valid channel access token key IDs.
*/
@GET("oauth2/v2.1/tokens/kid")
Call<ChannelAccessTokenKeyIdsResponse> getsAllValidChannelAccessTokenKeyIds(
@Query("client_assertion_type") String clientAssertionType,
@Query("client_assertion") String clientAssertion);

@POST("oauth2/v2.1/token")
@FormUrlEncoded
Call<IssueChannelAccessTokenResponse> issueChannelTokenByJWT(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
* Copyright 2021 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/

package com.linecorp.bot.model.oauth;

import java.util.List;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;

import com.linecorp.bot.model.oauth.ChannelAccessTokenKeyIdsResponse.ChannelAccessTokenKeyIdsResponseBuilder;

import lombok.Builder;
import lombok.Value;

@Value
@Builder
@JsonDeserialize(builder = ChannelAccessTokenKeyIdsResponseBuilder.class)
public class ChannelAccessTokenKeyIdsResponse {
/**
* Array of channel access token key IDs.
*/
List<String> kids;

@JsonPOJOBuilder(withPrefix = "")
public static class ChannelAccessTokenKeyIdsResponseBuilder {
// Filled by lombok.
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,12 @@ public class IssueChannelAccessTokenResponse {
@JsonProperty("token_type")
String tokenType = "Bearer";

/**
* Unique key ID for identifying the channel access token.
*/
@JsonProperty("key_id")
String keyId;

@JsonPOJOBuilder(withPrefix = "")
public static class IssueChannelAccessTokenResponseBuilder {
// Filled by lombok.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
* Copyright 2021 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/

package com.linecorp.bot.model.oauth;

import static java.lang.ClassLoader.getSystemResourceAsStream;
import static org.assertj.core.api.Assertions.assertThat;

import java.io.InputStream;

import org.junit.Test;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.linecorp.bot.model.testutil.TestUtil;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class OAuthDeserializeTest {
@Test
public void testIssueChannelAccessToken() {
final IssueChannelAccessTokenResponse target =
parse("oauth/oauth2/v2.1/token.json", IssueChannelAccessTokenResponse.class);

assertThat(target.getAccessToken()).isEqualTo("eyJhbGciOiJIUz.....");
assertThat(target.getTokenType()).isEqualTo("Bearer");
assertThat(target.getExpiresInSecs()).isEqualTo(2592000L);
assertThat(target.getKeyId()).isEqualTo("sDTOzw5wIfxxxxPEzcmeQA");
}

@Test
public void testTokenKids() {
final ChannelAccessTokenKeyIdsResponse target =
parse("oauth/oauth2/v2.1/tokens/kid.json", ChannelAccessTokenKeyIdsResponse.class);

assertThat(target.getKids()).hasSize(6);
assertThat(target.getKids().get(0)).isEqualTo("U_gdnFYKTWRxxxxDVZexGg");
assertThat(target.getKids().get(5)).isEqualTo("G82YP96jhHwyKSxxxx7IFA");
}

@SneakyThrows
private static <T> T parse(final String resourceName, final Class<T> clazz) {
final ObjectMapper objectMapper = TestUtil.objectMapperWithProductionConfiguration(true);

try (InputStream is = getSystemResourceAsStream(resourceName)) {
return objectMapper.readValue(is, clazz);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"access_token": "eyJhbGciOiJIUz.....",
"token_type": "Bearer",
"expires_in": 2592000,
"key_id": "sDTOzw5wIfxxxxPEzcmeQA"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"kids": [
"U_gdnFYKTWRxxxxDVZexGg",
"sDTOzw5wIfWxxxxzcmeQA",
"73hDyp3PxGfxxxxD6U5qYA",
"FHGanaP79smDxxxxyPrVw",
"CguB-0kxxxxdSM3A5Q_UtQ",
"G82YP96jhHwyKSxxxx7IFA"
]
}