How to migrate from PrivateKeyByes to PrivateKey on the ASPNET OAuth Provider

240 Views Asked by At

Currently I'm running the AspNet.Security.OAuth.Apple package with version 3.1.7. I'm upgrading to .NET 6 and thereby upgrade this AspNet.Security.OAuth.Apple package to 6.0.0 as well.

There is a breaking change announced here. It tells us to migrate from the byte[] property of PrivateKeyBytes to the ReadOnlyMemory<char> property called PrivateKey.

I can't get it to work, so I hope anyone can help me.

Current working code:

<..>
string appleKeySecret = configuration.GetValue("AppSettings:AppleKeySecret", 
string.Empty);
<...>

authenticationBuilder.AddApple("Apple", "Apple", options =>
{
    options.SignInScheme = AuthenticationSchemeConstants.ExternalCookieAuthenticationScheme;

    options.ClientId = appleClientId;
    options.KeyId = appleKeyId;
    options.TeamId = appleTeamId;

    options.GenerateClientSecret = true;
                    
    options.PrivateKeyBytes = _ => Task.FromResult(Convert.FromBase64String(appleKeySecret));
});

Migrated code that returns the following error:

Failed to generate new client secret for the Apple authentication scheme. No supported key formats were found. Check that the input represents the contents of a PEM-encoded key file, not the path to such a file. (Parameter 'input')

authenticationBuilder.AddApple("Apple", "Apple", options =>
{
    options.SignInScheme = AuthenticationSchemeConstants.ExternalCookieAuthenticationScheme;

    options.ClientId = appleClientId;
    options.KeyId = appleKeyId;
    options.TeamId = appleTeamId;

    options.GenerateClientSecret = true;

    options.PrivateKey = (keyId, _) =>
    {
        return Task.FromResult(appleKeySecret.AsMemory());
    };
});

So the private key content of the "AppSettings:AppleKeySecret" configuration is correct, or it won't work on the 3.1.7 version as well. I assume I'm not fully aware on how to work with this certificate content.

Any tips on how to get this PrivateKeyBytes working?

Many thanks in advance!

1

There are 1 best solutions below

0
JonHendrix On

It's fixed when I add the -----BEGIN PRIVATE KEY----- at the beginning and -----END PRIVATE KEY----- at the end of the value.

var withPem = 
 string.Format("-----BEGIN PRIVATE KEY-----\n{0}\n-----END PRIVATE KEY-----", appleKeySecret);

authenticationBuilder.AddApple("Apple", "Apple", options =>
{
    options.SignInScheme = AuthenticationSchemeConstants.ExternalCookieAuthenticationScheme;

    options.ClientId = appleClientId;
    options.KeyId = appleKeyId;
    options.TeamId = appleTeamId;

    options.GenerateClientSecret = true;

    options.PrivateKey = (keyId, _) =>
    {
        return Task.FromResult(withPem.AsMemory());
    };
});