由Apereo CAS发布的具有网络核心加密JWT的解码

时间:2019-07-02 21:15:48

标签: .net-core jwt cas jwe

Apereo CAS单一登录发布了以下JWT。

eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.ZXlKNmFYQWlPaUpFUlVZaUxDSmhiR2NpT2lKa2FYSWlMQ0psYm1NaU9pSkJNVEk0UTBKRExVaFRNalUySWl3aWRIbHdJam9pU2xkVUluMC4uREJXMFNUa19OSUVrMmFCVElJNHVnUS5qX3l4a1BVOHNzQ2tCUkdrdjN2RGI0QjFyVDRHWEhzRUJtTlJvTVR0d0hvMjc0NF96cHIzaW1JUk15ek1nU0RIcF9xcXFIQVVnNUNvM3JuM0FTQWUzS1VaMmFsR1B1SmIzT3UxN0hGR2t6a0RDS29CamdHdU9LVHowMlpfVWpYcm1hZXg0RDVyOUt1blNZYWxTWVBDTFU3TncyZEZVWHBwWnlrb3pQdXl6RFFadjZVMDlQaXgxa1gtLW9obUpFVUZJWlN6Vi1DQUs1RTRsSmtWU3ZrZ1gxSmVBMkVjNlY4aFJUSzFIMXRmb2t6Y09nNlJXNElWN05JNVJUQW8ycmlIVlVnLV94czZIY2JFcFZxR0hlVW5QNmF0Nl9zLTFnbGMzTTFzeHBJcmxBN3FEblhPUGt1ZjFmbnpwcEpFVmZWVTV2LWpOUDZQQ0ZnMjA2S2pjeDBYYlRVX0hWN1NyUUhyWUx2Y0gwVWlWVjljZGNOWmJ0Q2hjQjkwX2M2YXVRVmZjeEJZZjE1c2V0M2g3MzA0T0w5RmM5MG5fbXNyV3RIMnVYcGxfUEEwc29IMnJMM0xVV3YyS1E0WE5lR0V5eXpqRXBZWTU3VzJMazZreWQ2UU13RV9ndy5TenQ3WGFqbTBnSy11bk05djl5azdB.V50nzzET85j2FAMRGCLqN1sLXZ8WZrfH0G5__WL6UwvrjAZbvj9tjXAnwcIoBeyFU-zvIsjom520-p2JCNoqEg

我知道它是使用JWE standard的加密JWT。加密密钥如下。

9O22Vd7QJu3mBNhOy8vwZaSH1UPdieWAj4f9si2q-O8

签名秘诀如下。

9O22Vd7QJu3mBNhOy8vwZaSH1UPdieWAj4f9si2q-O89O22Vd7QJu3mBNhOy8vwZaSH1UPdieWAj4f9si2q-O8

以下是用于正确解码此JWT的Java代码。

    public Assertion validate(String ticket) throws TicketValidationException {
        try {
            System.out.println("ticket="+ticket);

            final Key key = new AesKey(signingKey.getBytes(StandardCharsets.UTF_8));

            final JsonWebSignature jws = new JsonWebSignature();
            jws.setCompactSerialization(ticket);
            jws.setKey(key);
            if (!jws.verifySignature()) {
                throw new TicketValidationException("JWT verification failed");
            }

            final byte[] decodedBytes = Base64.decodeBase64(jws.getEncodedPayload().getBytes(StandardCharsets.UTF_8));
            final String decodedPayload = new String(decodedBytes, StandardCharsets.UTF_8);

            final JsonWebEncryption jwe = new JsonWebEncryption();
            final JsonWebKey jsonWebKey = JsonWebKey.Factory
                    .newJwk("\n" + "{\"kty\":\"oct\",\n" + " \"k\":\"" + encryptionKey + "\"\n" + "}");

            jwe.setCompactSerialization(decodedPayload);
            jwe.setKey(new AesKey(jsonWebKey.getKey().getEncoded()));
            System.out.println("JWT ---> "+jwe.getPlaintextString());

            JSONParser parser = new JSONParser(JSONParser.DEFAULT_PERMISSIVE_MODE); 
            JSONObject json = (JSONObject) parser.parse(jwe.getPlaintextString());

            return new AssertionImpl(json.getAsString("sub"));

        } catch (JoseException | TicketValidationException ex) {
            logger.error(Arrays.toString(ex.getStackTrace()));
        } catch (ParseException ex) {
            java.util.logging.Logger.getLogger(CustomJWTValidator.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

我正在尝试在网络核心2.2中解码相同的JWT。代码如下。

    var encryptionKey = "9O22Vd7QJu3mBNhOy8vwZaSH1UPdieWAj4f9si2q-O8";
    var jsonWebKey = "\n" + "{\"kty\":\"oct\",\n" + " \"k\":\"" + encryptionKey + "\"\n" + "}";
    var jwkc = new JsonWebKey(jsonWebKey);
    services.AddAuthentication(x =>
    {
        x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
        options.RequireHttpsMetadata = false;
        options.SaveToken = true;
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = false,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("9O22Vd7QJu3mBNhOy8vwZaSH1UPdieWAj4f9si2q-O89O22Vd7QJu3mBNhOy8vwZaSH1UPdieWAj4f9si2q-O8")),
            ValidateIssuer = false,
            ValidateAudience = false,
            ValidateLifetime = false,
            TokenDecryptionKey = jwkc,
        };
    });

我故意禁用了签名验证和其他任何类型的验证。但是,在JWT验证中,我遇到以下错误。

System.ArgumentException: IDX12723: Unable to decode the payload 'ZXlKNmF...5azdB' as Base64Url encoded string. jwtEncodedString: ''. ---> Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: e. Path '', line 0, position 0.

似乎有效载荷未正确解码。到目前为止,很多Google搜索都没有给我带来任何结果。

1 个答案:

答案 0 :(得分:0)

我能够完全加载,验证签名并解密令牌。 问题出在您收到的密钥上:当没有一个签名时,encryption密钥已经被base64url安全编码。

对应的JWK是(分别是签名和加密):

  

{“ kty”:“ oct”,“ k”:“ OU8yMlZkN1FKdTNtQk5oT3k4dndaYVNIMVVQZGllV0FqNGY5c2kycS1PODlPMjJWZDdRSnUzbUJOaE95OHZ3WmFTSDFVUGRPt}

  

{“ kty”:“ oct”,“ k”:“ 9O22Vd7QJu3mBNhOy8vwZaSH1UPdieWAj4f9si2q-O8”}

编辑:为了记录,我使用了web-token/jwt-framework(PHP库)和以下脚本:

>>> foo = [[14, 3.5, b'Tom'], [18, -1.2, b'Larry'], [22, -1.7, b'Sue']]
>>> foo2 = mydecoder(foo)
>>> foo2
[[14, 3.5, 'Tom'], [18, -1.2, 'Larry'], [22, -1.7, 'Sue']]
>>> json.dumps(foo2)
'[[14, 3.5, "Tom"], [18, -1.2, "Larry"], [22, -1.7, "Sue"]]'