1

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

Question3r
  • 2,166
  • 19
  • 100
  • 200
  • 1
    Checkout reading static properties via reflection. E.g. https://stackoverflow.com/questions/451453/how-to-get-a-static-property-with-reflection – Jason Aug 12 '20 at 19:49

2 Answers2

1

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.

eocron
  • 6,885
  • 1
  • 21
  • 50
  • How about that? :) `if (!typeof(SecurityAlgorithms).GetFields().Any(fieldInfo => fieldInfo.Name.Equals(identitySettings.TokenSignatureAlgorithm))) // failed` – Question3r Aug 12 '20 at 19:57
  • You CAN use reflection if you want. It's just better that you not use it in general - you lose control over performance, over code you write, over code your collegues write. Try to unit test it, for example, or run it few thousand times and compare with straightforward. If it satisfies your business task - it is always good approach, but not always good in long term. – eocron Aug 12 '20 at 20:02
1

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();
AnGG
  • 679
  • 3
  • 9