1
votes

I have a MVC4 site that I have inherited. In the site it makes a call to an external system with the user's name & password and if all is ok it returns some data.

It is is very simple, but it requires a login page to prevent unauthorised access. The previous developer was new to MVC so they've put the [Authorize] attribute on the controller (good) but then realised that no MVC-authentication is happening so added [AllowAnonymous] to every action (bad). Because it is a simple site and has external authentication on each call to getting data, I do not want to add a database to the site and be creating users etc. but I want to use the Authorize attribute.

I think I can use forms authentication by storing a username & password in the website's config file (see here) e.g. username=Bob, pwd=abc123, and when the user logs in I call the external system and if I get data back I know the credentials are good. I can then log them in as Bob. When they click LogOut, I can log Bob out of the system.

If I do this though, will only one user be able to use the site at once? Because everybody will be logged in as Bob?

1

1 Answers

0
votes

It turns out that yes, this method was fine to use. Multiple users can browse the site because the cookie is downloaded to the browser to grant them access. If my site did something based on the logged in user, then it would not be a viable option. But for simply knowing that their credentials have been verified and keeping out users without authorisation, it works well.

The web config looks a little like this:

<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880">
    <credentials passwordFormat="SHA1" >
      <user name="Bob"
            password="a78b235b6b439925569a989863andmoredigitsandletters"/>
    </credentials>
  </forms>
</authentication>
<sessionState timeout="30" />

You can generate a SHA-1 password by typing in your chosen password into one of the many sites on the web that offer this service.

In the code, once the user's form data has been verified by the external system we log in the known user with their name and the non-hashed password:

if (FormsAuthentication.Authenticate("Bob", "p4$$w0rd"))
{
     FormsAuthentication.SetAuthCookie("Bob", false);
}

Now the user can access [Authorize] actions and methods.