Pergunta

I want to generate client id and client secret using .NET. I read the OAuth 2 specification and for example the size of client secret is not specified there. Is there a good practice for generating client id and client secret using .NET framework???

Foi útil?

Solução

As section 2.2 of The OAuth 2.0 Authorization Framework says:

The authorization server issues the registered client a client identifier -- a unique string representing the registration information provided by the client. The client identifier is not a secret; it is exposed to the resource owner and MUST NOT be used alone for client authentication. The client identifier is unique to the authorization server.

The client identifier string size is left undefined by this specification. The client should avoid making assumptions about the identifier size. The authorization server SHOULD document the size of any identifier it issues.

So you can define the client identifier by yourself. It depends your choice. You can use System.Guid to generate one simply, or use uid + systemTime, also you can Hash it, encrypt it or anything you want else.

But the client secret should be a cryptographically strong random string. You can generate one like this:

RandomNumberGenerator cryptoRandomDataGenerator = new RNGCryptoServiceProvider();
byte[] buffer = new byte[length];
cryptoRandomDataGenerator.GetBytes(buffer);
string uniq = Convert.ToBase64String(buffer);
return uniq;

Also you can use cryptographic hash functions() to hash UUID+SystemTime+somthingelse to implement it yourself.

If you want to know more practices, you can refer to some open implementations from here.

Outras dicas

Here is the code to generate a ClientSecret key in PowerShell

$bytes = New-Object Byte[] 32
$rand = [System.Security.Cryptography.RandomNumberGenerator]::Create()
$rand.GetBytes($bytes)
$rand.Dispose()
$newClientSecret = [System.Convert]::ToBase64String($bytes)
$newClientSecret

I found it here https://learn.microsoft.com/en-us/sharepoint/dev/sp-add-ins/replace-an-expiring-client-secret-in-a-sharepoint-add-in#generate-a-new-secret

The appendices A.1 and A.2 define the format for both the client_id and client_secret in their ABNF grammar as *VSCHAR where VSCHAR is defined as

VSCHAR     = %x20-7E

meaning the set of printable ASCII characters. The length of the client_id is left unspecified by the spec, as noted by @Owen Tsao. This means that although you can select a random sequence of bytes and encode them in base64, the set of characters that appear in base64 represent only a strict subset of those available for use in this application.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top