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

Issue #4128 - test the decoding of OpenId Credentials #4166

Merged
merged 11 commits into from Nov 20, 2019
@@ -0,0 +1,96 @@
//
// ========================================================================
// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//

package org.eclipse.jetty.security.openid;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.Map;

import org.eclipse.jetty.util.ajax.JSON;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;

/**
* Used to decode the ID Token from the base64 encrypted JSON Web Token (JWT).
*/
public class JwtDecoder
{
private static final Logger LOG = Log.getLogger(JwtDecoder.class);

/**
* Decodes a JSON Web Token (JWT) into a Map of claims.
* @param jwt the JWT to decode.
* @return the map of claims encoded in the JWT.
*/
public static Map<String, Object> decode(String jwt)
{
if (LOG.isDebugEnabled())
LOG.debug("decode {}", jwt);

String[] sections = jwt.split("\\.");
if (sections.length != 3)
throw new IllegalArgumentException("JWT does not contain 3 sections");

Base64.Decoder decoder = Base64.getUrlDecoder();
lachlan-roberts marked this conversation as resolved.
Show resolved Hide resolved
String jwtHeaderString = new String(decoder.decode(padJWTSection(sections[0])), StandardCharsets.UTF_8);
String jwtClaimString = new String(decoder.decode(padJWTSection(sections[1])), StandardCharsets.UTF_8);
String jwtSignature = sections[2];

Map<String, Object> jwtHeader = (Map)JSON.parse(jwtHeaderString);
if (LOG.isDebugEnabled())
LOG.debug("JWT Header: {}", jwtHeader);

/* If the ID Token is received via direct communication between the Client
and the Token Endpoint (which it is in this flow), the TLS server validation
MAY be used to validate the issuer in place of checking the token signature. */
if (LOG.isDebugEnabled())
LOG.debug("JWT signature not validated {}", jwtSignature);

return (Map)JSON.parse(jwtClaimString);
}

static byte[] padJWTSection(String unpaddedEncodedJwtSection)
{
// If already padded just use what we are given.
if (unpaddedEncodedJwtSection.endsWith("="))
return unpaddedEncodedJwtSection.getBytes();

int length = unpaddedEncodedJwtSection.length();
int remainder = length % 4;

// A valid base-64-encoded string will have a remainder of 0, 2 or 3. Never 1!
if (remainder == 1)
throw new IllegalArgumentException("Not a valid Base64-encoded string");

byte[] paddedEncodedJwtSection;
if (remainder > 0)
{
int paddingNeeded = (4 - remainder) % 4;
paddedEncodedJwtSection = Arrays.copyOf(unpaddedEncodedJwtSection.getBytes(), length + paddingNeeded);
Arrays.fill(paddedEncodedJwtSection, length, paddedEncodedJwtSection.length, (byte)'=');
}
else
{
paddedEncodedJwtSection = unpaddedEncodedJwtSection.getBytes();
}

return paddedEncodedJwtSection;
}
}
Expand Up @@ -26,8 +26,6 @@
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.Map;

import org.eclipse.jetty.util.IO;
Expand Down Expand Up @@ -104,7 +102,7 @@ public void redeemAuthCode() throws IOException
if (!"Bearer".equalsIgnoreCase(tokenType))
throw new IllegalArgumentException("invalid token_type");

claims = decodeJWT(idToken);
claims = JwtDecoder.decode(idToken);
if (LOG.isDebugEnabled())
LOG.debug("claims {}", claims);
validateClaims();
Expand Down Expand Up @@ -172,58 +170,6 @@ public boolean isExpired()
return false;
}

protected Map<String, Object> decodeJWT(String jwt) throws IOException
{
if (LOG.isDebugEnabled())
LOG.debug("decodeJWT {}", jwt);

String[] sections = jwt.split("\\.");
if (sections.length != 3)
throw new IllegalArgumentException("JWT does not contain 3 sections");

Base64.Decoder decoder = Base64.getUrlDecoder();
String jwtHeaderString = new String(decoder.decode(padJWTSection(sections[0])), StandardCharsets.UTF_8);
String jwtClaimString = new String(decoder.decode(padJWTSection(sections[1])), StandardCharsets.UTF_8);
String jwtSignature = sections[2];

Map<String, Object> jwtHeader = (Map)JSON.parse(jwtHeaderString);
LOG.debug("JWT Header: {}", jwtHeader);

/* If the ID Token is received via direct communication between the Client
and the Token Endpoint (which it is in this flow), the TLS server validation
MAY be used to validate the issuer in place of checking the token signature. */
if (LOG.isDebugEnabled())
LOG.debug("JWT signature not validated {}", jwtSignature);

return (Map)JSON.parse(jwtClaimString);
}

private static byte[] padJWTSection(String unpaddedEncodedJwtSection)
{
int length = unpaddedEncodedJwtSection.length();
int remainder = length % 4;

if (remainder == 1)
// A valid base64-encoded string will never be have an odd number of characters.
throw new IllegalArgumentException("Not valid Base64-encoded string");

byte[] paddedEncodedJwtSection;

if (remainder > 0)
{
int paddingNeeded = (4 - remainder) % 4;

paddedEncodedJwtSection = Arrays.copyOf(unpaddedEncodedJwtSection.getBytes(), length + paddingNeeded);
Arrays.fill(paddedEncodedJwtSection, length, paddedEncodedJwtSection.length, (byte)'=');
}
else
{
paddedEncodedJwtSection = unpaddedEncodedJwtSection.getBytes();
}

return paddedEncodedJwtSection;
}

private Map<String, Object> claimAuthCode(String authCode) throws IOException
{
if (LOG.isDebugEnabled())
Expand Down
@@ -0,0 +1,99 @@
//
// ========================================================================
// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//

package org.eclipse.jetty.security.openid;

import java.util.Map;
import java.util.stream.Stream;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertThrows;

public class JwtDecoderTest
{
public static Stream<Arguments> paddingExamples()
{
return Stream.of(
Arguments.of("XXXX", "XXXX"),
Arguments.of("XXX", "XXX="),
Arguments.of("XX", "XX=="),
Arguments.of("XXX=", "XXX="),
Arguments.of("X-X", "X-X="),
Arguments.of("@#", "@#=="),
Arguments.of("X=", "X="),
Arguments.of("XX=", "XX="),
Arguments.of("XX==", "XX=="),
Arguments.of("XXX=", "XXX="),
Arguments.of("", "")
lachlan-roberts marked this conversation as resolved.
Show resolved Hide resolved
);
}

public static Stream<Arguments> badPaddingExamples()
{
return Stream.of(
Arguments.of("X"),
Arguments.of("XXXXX")
);
}

@ParameterizedTest
@MethodSource("paddingExamples")
public void testPaddingBase64(String input, String expected)
{
byte[] actual = JwtDecoder.padJWTSection(input);
assertThat(actual, is(expected.getBytes()));
}

@ParameterizedTest
@MethodSource("badPaddingExamples")
public void testPaddingInvalidBase64(String input)
{
IllegalArgumentException error = assertThrows(IllegalArgumentException.class,
() -> JwtDecoder.padJWTSection(input));

assertThat(error.getMessage(), is("Not a valid Base64-encoded string"));
}

@Test
public void testEncodeDecode()
{
String issuer = "example.com";
String subject = "1234";
String clientId = "1234.client.id";
String name = "Bob";
long expiry = 123;

// Create a fake ID Token.
String claims = JwtEncoder.createIdToken(issuer, clientId, subject, name, expiry);
String idToken = JwtEncoder.encode(claims);

// Decode the ID Token and verify the claims are the same.
Map<String, Object> decodedClaims = JwtDecoder.decode(idToken);
assertThat(decodedClaims.get("iss"), is(issuer));
assertThat(decodedClaims.get("sub"), is(subject));
assertThat(decodedClaims.get("aud"), is(clientId));
assertThat(decodedClaims.get("name"), is(name));
assertThat(decodedClaims.get("exp"), is(expiry));
}
}
@@ -0,0 +1,52 @@
//
// ========================================================================
// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//

package org.eclipse.jetty.security.openid;

import java.util.Base64;

public class JwtEncoder
lachlan-roberts marked this conversation as resolved.
Show resolved Hide resolved
{
private static final Base64.Encoder ENCODER = Base64.getUrlEncoder();
private static final String DEFAULT_HEADER = "{\"INFO\": \"this is not used or checked in our implementation\"}";
private static final String DEFAULT_SIGNATURE = "we do not validate signature as we use the authorization code flow";

public static String encode(String idToken)
{
return stripPadding(ENCODER.encodeToString(DEFAULT_HEADER.getBytes())) + "." +
stripPadding(ENCODER.encodeToString(idToken.getBytes())) + "." +
stripPadding(ENCODER.encodeToString(DEFAULT_SIGNATURE.getBytes()));
}

private static String stripPadding(String paddedBase64)
{
return paddedBase64.split("=")[0];
}

public static String createIdToken(String provider, String clientId, String subject, String name, long expiry)
{
return "{" +
lachlan-roberts marked this conversation as resolved.
Show resolved Hide resolved
"\"iss\": \"" + provider + "\"," +
"\"sub\": \"" + subject + "\"," +
"\"aud\": \"" + clientId + "\"," +
"\"exp\": " + expiry + "," +
"\"name\": \"" + name + "\"," +
"\"email\": \"" + name + "@example.com" + "\"" +
"}";
}
}
Expand Up @@ -149,8 +149,8 @@ public void testLoginLogout() throws Exception
content = response.getContentAsString().split("\n");
assertThat(content.length, is(3));
assertThat(content[0], is("userId: 123456789"));
assertThat(content[1], is("name: FirstName LastName"));
assertThat(content[2], is("email: FirstName@fake-email.com"));
assertThat(content[1], is("name: Alice"));
assertThat(content[2], is("email: Alice@example.com"));

// Request to admin page gives 403 as we do not have admin role
response = client.GET(appUriString + "/admin");
Expand Down