Question3r
Question3r

Reputation: 3812

How to check if string matches the name from any variable in a static class?

When creating a new SigningCredentials instance the second constructor parameter is the signatureAlgorithm of type string.

You don't have to use your own magic string, you can use static SecurityAlgorithms class e.g. SecurityAlgorithms.HmacSha256Signature.

I read the algorithm from a config file and want to validate this string. This string should contain a valid signatureAlgorithm. Is there a simple way I could say

(Pseudo Code)

if (SecurityAlgorithms.Contains(identitySettings.TokenSignatureAlgorithm))
{
    // validation failed
}

so that one is not able to configure crap like identitySettings.TokenSignatureAlgorithm = "this is no algorithm";

Upvotes: 1

Views: 1456

Answers (2)

AnGG
AnGG

Reputation: 831

You can see what is happening when you pass wrong alorithm string, and then catch it :

try
{
    var signCredentials = new SigningCredentials(a,b,c,d);
}
catch(Exception e)
{
// validation failed
}

the second option is to use Reflaction

something list this :

string[] algs = typeof(SecurityAlgorithms)
.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)
.Select(pi => pi.GetRawConstantValue().ToString())
.ToArray();

Upvotes: 1

eocron
eocron

Reputation: 7546

Without using reflection magic it is as simple as that:

private readonly HashSet<string> _allowedSecurityAlgorithms = new HashSet<string>(StringComparison.OrdinalIgnoreCase) 
    {
        SecurityAlgorithms.A, 
        SecurityAlgorithms.B, 
        SecurityAlgorithms.C
    };

if (!_allowedSecurityAlgorithms.Contains(identitySettings.TokenSignatureAlgorithm))
{
    // validation failed
}

PS

I purposelly didn't use reflection to solve your task, because controlling validation is often a must. If you still want to be "bad boy", here you go - How can I get all constants of a type by reflection?

Just initialize _allowedSecurityAlgorithms with constants returned from any method described there.

Upvotes: 1

Related Questions