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

Support fetching the JWKS #260

Merged
merged 3 commits into from
Nov 6, 2019
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
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,11 @@
import com.auth0.android.result.UserProfile;
import com.auth0.android.util.Telemetry;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.okhttp.HttpUrl;
import com.squareup.okhttp.OkHttpClient;

import java.security.PublicKey;
import java.util.Map;

import static com.auth0.android.authentication.ParameterBuilder.GRANT_TYPE_AUTHORIZATION_CODE;
Expand Down Expand Up @@ -98,10 +100,11 @@ public class AuthenticationAPIClient {
private static final String USER_INFO_PATH = "userinfo";
private static final String REVOKE_PATH = "revoke";
private static final String HEADER_AUTHORIZATION = "Authorization";
private static final String WELL_KNOWN_PATH = ".well-known";
private static final String JWKS_FILE_PATH = "jwks.json";

private final Auth0 auth0;
@VisibleForTesting
final OkHttpClient client;
private final OkHttpClient client;
private final Gson gson;
private final RequestFactory factory;
private final ErrorBuilder<AuthenticationException> authErrorBuilder;
Expand Down Expand Up @@ -1075,6 +1078,22 @@ public TokenRequest token(@NonNull String authorizationCode, @NonNull String red
return new TokenRequest(request);
}

/**
* Creates a new Request to obtain the JSON Web Keys associated with the Auth0 account under the given domain.
* Only supports RSA keys used for signatures (Public Keys).
*
* @return a request to obtain the JSON Web Keys associated with this Auth0 account.
*/
public Request<Map<String, PublicKey>, AuthenticationException> fetchJsonWebKeys() {
HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder()
.addPathSegment(WELL_KNOWN_PATH)
.addPathSegment(JWKS_FILE_PATH)
.build();
TypeToken<Map<String, PublicKey>> jwksType = new TypeToken<Map<String, PublicKey>>() {
};
return factory.GET(url, client, gson, jwksType, authErrorBuilder);
}

private AuthenticationRequest loginWithToken(Map<String, Object> parameters) {
HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder()
.addPathSegment(OAUTH_PATH)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,28 @@
import com.auth0.android.util.JsonRequiredTypeAdapterFactory;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.security.PublicKey;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;

public abstract class GsonProvider {

static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";

public static Gson buildGson() {
Type jwksType = new TypeToken<Map<String, PublicKey>>() {
}.getType();

return new GsonBuilder()
.registerTypeAdapterFactory(new JsonRequiredTypeAdapterFactory())
.registerTypeAdapter(UserProfile.class, new UserProfileDeserializer())
.registerTypeAdapter(Credentials.class, new CredentialsDeserializer())
.registerTypeAdapter(jwksType, new JwksDeserializer())
.setDateFormat(DATE_FORMAT)
.create();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package com.auth0.android.request.internal;

import android.util.Base64;
import android.util.Log;

import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;

import java.lang.reflect.Type;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

class JwksDeserializer implements JsonDeserializer<Map<String, PublicKey>> {

private static final String RSA_ALGORITHM = "RS256";
private static final String USE_SIGNING = "sig";

@Override
public Map<String, PublicKey> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
if (!json.isJsonObject() || json.isJsonNull() || json.getAsJsonObject().entrySet().isEmpty()) {
throw new JsonParseException("jwks json must be a valid and non-empty json object");
}

HashMap<String, PublicKey> jwks = new HashMap<>();

JsonObject object = json.getAsJsonObject();
JsonArray keys = object.getAsJsonArray("keys");
for (JsonElement k : keys) {
JsonObject currentKey = k.getAsJsonObject();
String keyAlg = context.deserialize(currentKey.get("alg"), String.class);
String keyUse = context.deserialize(currentKey.get("use"), String.class);
if (!RSA_ALGORITHM.equals(keyAlg) || !USE_SIGNING.equals(keyUse)) {
//Key not supported at this time
continue;
}
String keyType = context.deserialize(currentKey.get("kty"), String.class);
String keyId = context.deserialize(currentKey.get("kid"), String.class);
String keyModulus = context.deserialize(currentKey.get("n"), String.class);
String keyPublicExponent = context.deserialize(currentKey.get("e"), String.class);

try {
KeyFactory kf = KeyFactory.getInstance(keyType);
BigInteger modulus = new BigInteger(1, Base64.decode(keyModulus, Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_WRAP));
BigInteger exponent = new BigInteger(1, Base64.decode(keyPublicExponent, Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_WRAP));
PublicKey pub = kf.generatePublic(new RSAPublicKeySpec(modulus, exponent));
jwks.put(keyId, pub);
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
Log.e(JwksDeserializer.class.getSimpleName(), "Could not parse the JWK with ID " + keyId, e);
//Would result in an empty key set
}
}
return Collections.unmodifiableMap(jwks);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,12 @@ public <T, U extends Auth0Exception> ParameterizableRequest<T, U> GET(HttpUrl ur
return request;
}

public <T, U extends Auth0Exception> ParameterizableRequest<T, U> GET(HttpUrl url, OkHttpClient client, Gson gson, TypeToken<T> typeToken, ErrorBuilder<U> errorBuilder) {
final ParameterizableRequest<T, U> request = createSimpleRequest(url, client, gson, "GET", typeToken, errorBuilder);
addMetrics(request);
return request;
}

private <T, U extends Auth0Exception> void addMetrics(ParameterizableRequest<T, U> request) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
request.addHeader(entry.getKey(), entry.getValue());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@
import org.robolectric.annotation.Config;

import java.lang.reflect.Type;
import java.security.PublicKey;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
Expand Down Expand Up @@ -1517,6 +1519,36 @@ public void shouldSendSMSLinkAndroidSync() throws Exception {
assertThat(body, hasEntry("connection", "sms"));
}

@Test
public void shouldFetchJsonWebKeys() throws Exception {
mockAPI.willReturnSuccessfulJsonWebKeys();

MockAuthenticationCallback<Map<String, PublicKey>> callback = new MockAuthenticationCallback<>();
client.fetchJsonWebKeys()
.start(callback);

final RecordedRequest request = mockAPI.takeRequest();
assertThat(request.getPath(), equalTo("/.well-known/jwks.json"));
assertThat(request.getHeader("Accept-Language"), is(getDefaultLocale()));

assertThat(callback, hasPayload(Collections.<String, PublicKey>emptyMap()));
}

@Test
public void shouldFetchJsonWebKeysSync() throws Exception {
mockAPI.willReturnSuccessfulJsonWebKeys();

Map<String, PublicKey> result = client.fetchJsonWebKeys()
.execute();

final RecordedRequest request = mockAPI.takeRequest();
assertThat(request.getPath(), equalTo("/.well-known/jwks.json"));
assertThat(request.getHeader("Accept-Language"), is(getDefaultLocale()));

assertThat(result, is(notNullValue()));
assertThat(result, is(Collections.<String, PublicKey>emptyMap()));
}

@Test
public void shouldFetchProfileAfterLoginRequest() throws Exception {
mockAPI.willReturnSuccessfulLogin()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.auth0.android.request.internal;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.FileNotFoundException;
import java.io.FileReader;
Expand All @@ -15,6 +16,10 @@ abstract class GsonBaseTest {

Gson gson;

<T> T pojoFrom(Reader json, TypeToken<T> typeToken) throws IOException {
return gson.getAdapter(typeToken).fromJson(json);
}

<T> T pojoFrom(Reader json, Class<T> clazz) throws IOException {
return gson.getAdapter(clazz).fromJson(json);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
package com.auth0.android.request.internal;

import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.math.BigInteger;
import java.security.PublicKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Map;

import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

@RunWith(RobolectricTestRunner.class)
@Config(sdk = 21)
public class JwksGsonTest extends GsonBaseTest {
private static final String VALID_RSA_JWKS = "src/test/resources/jwks_rsa.json";
private static final String EXPECTED_KEY_ID = "RUVBOTVEMEZBMTA5NDAzNEQzNTZGNzMyMTI4MzU1RkNFQzhCQTM0Mg";
private static final String EXPECTED_RSA_EXPONENT = "65537";
private static final String EXPECTED_RSA_MODULUS = "2621148833618669851632627030508577941932991104442742159327628027691656119517675178227503934" +
"50126026383571140309353586180428305357637026071474336890156009441229041656542271917477199336983077844706495725045832557637658494403826" +
"343064304897328574182258821353161480771090757577522755330350956839942443917109665602066633259326057104246834759269337437620283600011255" +
"336891753201992873507788546321379785324808697815139356191481700515096717744643081207558743005545844515461091232322385145532862505800570" +
"17053908908888974416937916517307412534155165744508160026990874221314025481541880285443289277406354687335857437573080004037";

@Rule
public ExpectedException expectedException = ExpectedException.none();

@Before
public void setUp() {
gson = GsonProvider.buildGson();
}

@Test
public void shouldFailWithInvalidJson() throws Exception {
expectedException.expect(JsonParseException.class);
buildJwksFrom(json(INVALID));
}

@Test
public void shouldFailWithEmptyJson() throws Exception {
expectedException.expect(JsonParseException.class);
buildJwksFrom(json(EMPTY_OBJECT));
}

@Test
public void shouldReturnValid() throws Exception {
Map<String, PublicKey> jwks = buildJwksFrom(json(VALID_RSA_JWKS));
assertThat(jwks, is(notNullValue()));
assertThat(jwks.size(), is(1));
assertTrue(jwks.containsKey(EXPECTED_KEY_ID));
PublicKey pub = jwks.get(EXPECTED_KEY_ID);
assertThat(pub, instanceOf(RSAPublicKey.class));

RSAPublicKey rsaPub = (RSAPublicKey) pub;
assertThat(rsaPub.getPublicExponent(), is(new BigInteger(EXPECTED_RSA_EXPONENT)));
assertThat(rsaPub.getModulus(), is(new BigInteger(EXPECTED_RSA_MODULUS)));
}

@Test
public void shouldReturnEmptyWhenKeysAreEmpty() throws Exception {
Map<String, PublicKey> jwks = buildJwksFrom(new StringReader("{\"keys\": []}"));
assertThat(jwks, is(notNullValue()));
assertTrue(jwks.isEmpty());
}

@Test
public void shouldReturnEmptyWhenKeysAreFromDifferentAlgorithm() throws Exception {
Map<String, PublicKey> jwks = buildJwksFrom(new StringReader("{\"keys\": [{\"alg\": \"RS512\", \"use\": \"sig\"}]}"));
assertThat(jwks, is(notNullValue()));
assertTrue(jwks.isEmpty());
}

@Test
public void shouldReturnEmptyWhenKeysAreNotForSignatureChecking() throws Exception {
Map<String, PublicKey> jwks = buildJwksFrom(new StringReader("{\"keys\": [{\"alg\": \"RS256\", \"use\": \"enc\"}]}"));
assertThat(jwks, is(notNullValue()));
assertTrue(jwks.isEmpty());
}

@Test
public void shouldReturnEmptyWhenKeysCannotBeCreatedBecauseOfNotSupportedKeyType() throws Exception {
Map<String, PublicKey> jwks = buildJwksFrom(new StringReader("{\"keys\": [{\"alg\": \"RS256\", \"use\": \"sig\", \"kty\": \"INVALID_VALUE\"}]}"));
assertThat(jwks, is(notNullValue()));
assertTrue(jwks.isEmpty());
}

private Map<String, PublicKey> buildJwksFrom(Reader json) throws IOException {
TypeToken<Map<String, PublicKey>> jwksType = new TypeToken<Map<String, PublicKey>>() {
};
return pojoFrom(json, jwksType);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public class RequestFactoryTest {
private static final String METHOD_POST = "POST";
private static final String METHOD_PATCH = "PATCH";
private static final String METHOD_DELETE = "DELETE";
private static final String METHOD_GET = "GET";
private static final String CLIENT_INFO = "client_info";
private static final String USER_AGENT = "user_agent";
private static final String TOKEN = "token";
Expand Down Expand Up @@ -157,6 +158,25 @@ public void shouldCreateDELETERequestOfTToken() {
assertThat(request, RequestMatcher.hasArguments(url, METHOD_DELETE, typeToken));
}

@Test
public void shouldCreateGETRequest() {
final ParameterizableRequest<Auth0, Auth0Exception> request = factory.GET(url, client, gson, Auth0.class, builder);

assertThat(request, is(notNullValue()));
assertThat(request, hasHeaders(RequestFactory.getDefaultLocale(), CLIENT_INFO, USER_AGENT));
assertThat(request, RequestMatcher.hasArguments(url, METHOD_GET, Auth0.class));
}

@Test
public void shouldCreateGETRequestOfTToken() {
TypeToken<Auth0> typeToken = createTypeToken();
final ParameterizableRequest<Auth0, Auth0Exception> request = factory.GET(url, client, gson, typeToken, builder);

assertThat(request, is(notNullValue()));
assertThat(request, hasHeaders(RequestFactory.getDefaultLocale(), CLIENT_INFO, USER_AGENT));
assertThat(request, RequestMatcher.hasArguments(url, METHOD_GET, typeToken));
}

@Test
public void shouldGetDefaultLocale() {
final Locale localeJP = new Locale("ja", "JP");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,14 @@ public AuthenticationAPI willReturnFailedLogin() {
return this;
}

public AuthenticationAPI willReturnSuccessfulJsonWebKeys() {
String json = "{" +
"\"keys\": []" +
"}";
server.enqueue(responseWithJSON(json, 200));
return this;
}

public AuthenticationAPI willReturnTokenInfo() {
String json = "{\n" +
" \"email\": \"p@p.xom\",\n" +
Expand Down
16 changes: 16 additions & 0 deletions auth0/src/test/resources/jwks_rsa.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"keys": [
{
"alg": "RS256",
"kty": "RSA",
"use": "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