skip to Main Content

I am building a MVC app in asp.net core 6. The app is done but I want it to be used only by selected few users.
I want these users to be stored in a file so that they can be added later by a SYSadmin.
Right now I am using the following code:

{
    var policy = new AuthorizationPolicyBuilder()
                   .RequireAssertion(x =>
                         x.User.Identity!.Name == "DOMAIN\NAME" ||
                         x.User.Identity!.Name == "DOMAIN2\NAME2"
                         )
                   .Build();
    config.Filters.Add(new AuthorizeFilter(policy));
});

I would like this to be replaced with a code which reads the allowed users from a file.
Thank you.

2

Answers


  1. Based on the question and it’s comment, I’m assuming a simple text file containing users separated by line-breaks is good enough – something like this:

    DOMAIN1UserA
    DOMAIN2UserB
    DOMAIN3UserC
    

    If that is the case, you can use File.ReadAllLines() to load the content of the file into a string array, and then simply use linq’s Any():

    // Note: filePath should come from app.settings
    var users = File.ReadAllLines(filePath);
    
    // validation on the content of users omitted for brevity
    
    {
        var policy = new AuthorizationPolicyBuilder()
                       .RequireAssertion(x =>
                             users.Any(
                                 u => u.Equals(
                                     x.User.Identity!.Name, StringComparison.OrdinalIgnoreCase
                                 )
                             )
                        )
                       .Build();
        config.Filters.Add(new AuthorizeFilter(policy));
    });
    

    Notes:

    1. You should wrap your call to File.ReadAllLines() with a try...catch to handle exceptions that might be thrown from it in case the path is wrong or the user running the application don’t have permissions to the file.
      If you can’t get the information from the file, you should exit gracefully or consider using a default user (hard coded or app.settings based).

    2. As a rule, prefer using .Equals over == when comparing strings, especially if you want a case-insensitive comparosin. More info on string comparison can be found here: Recommendations
      for string usage
      .

    Login or Signup to reply.
  2. Here’s a version that reads the file every time, but only until a match is found. I. e. it doesn’t read the file only once at startup, so you can add and remove users at runtime:

        var policy = new AuthorizationPolicyBuilder()
            .RequireAssertion(async context => {
                    using var reader = new StreamReader(@"C:tempvalidusers.txt");
                    while (await reader.ReadLineAsync() is string validName)
                    {
                        if (string.Equals(context.User.Identity!.Name, validName, StringComparison.InvariantCultureIgnoreCase))
                            return true;
                    }
                    return false;                
                })
            .Build();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search