简体   繁体   中英

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 eg 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";

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM