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
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:
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’sAny()
:Notes:
You should wrap your call to
File.ReadAllLines()
with atry...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).
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: Recommendationsfor string usage.
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: