1

I am really confused right now on how would I implement authentication in ASP.NET MVC 5. This is my first time using ASP.NET MVC and I am used to desktop apps. There are a lot of terms thrown around like OWASP, OAuth, FormsAuthenticationTicket, and others that I am really having a hard time following.

I've decided is just to make a simple log in page for starters. Just check database for username and password and if exists, then user is authenticated. So far, based on what I've read, I can do so implementing IAuthenticationFilter. I have implemented OnAuthentication like so:

public void OnAuthentication(AuthenticationContext context)
{
    IIdentity ident = context.Principal.Identity;
    if (!ident.IsAuthenticated || !ident.Name == "randy") // Name is just for testing
    {
        context.Result = new HttpUnauthorizedResult();
    }
}

For OnAuthenticationChallenge, I just have code that redirects to a LogIn action method if user not authenticated (if result is HttpUnauthorizedResult and if user is not authenticated. Thinking about it, its like the same as logic OnAuthentication so why couldn't I just redirect then and there. I based these code on web examples).

In LogIn action method, there is a UserRepository that checks if a user exists. But if the user exists, I don't know how to set it the context's Principal. I don't know if I am doing this right so please comment on this.

I guess my questions would be:

  1. Is what I am doing correct?

  2. Why don't the examples in the web just redirect in OnAuthentication if the user is not authenticated. Why wait for OnAuthentication to execute?

  3. If what I am doing is correct, how do I set the Principal from the LogIn Action method? How do I clear it? And if I understand correctly, is this synonymous to logging in/logging out (setting principal/clearing principal)?

  4. If all I am doing is wrong, or even if it is right, could you direct me to where can I start learning authentication for ASP.NET MVC? When I search, the topics are for a specific implementation of something which mostly assumes understanding of some concepts. I'm having a hard time of where to start.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
g_b
  • 11,728
  • 9
  • 43
  • 80

2 Answers2

4

The confusion you're having is most likely due to the number of different authentication systems ASP.NET has gone through. You have ASP.NET Auth, SimpleMembership, which is really just a layer on top of ASP.NET Auth, and now Identity. Since you're using MVC 5, you should go with Identity. It's a top-down rewrite of authentication for ASP.NET and is much more powerful and extensible than previous iterations of authentication.

If you're just getting started, your best bet is to actually start with the Identity sample project. In Visual Studio, create a new empty MVC 5 application, and then run the following in Package Manager Console:

Install-Package Microsoft.AspNet.Identity.Samples -Pre

That will install a lot of other Nuget packages and give you a pretty much feature complete authentication workflow, including external "social" login providers, email confirmation, password reset, two-factor auth, etc.

However, don't build your application off of this sample project. You're going to make changes to all of this code for your application and you don't want the sample Nuget package getting in your way. Just use this project as a guide, and you can copy and paste relevant code over into your application, while making any necessary modifications. You also don't have to take everything. If you don't want two-factor auth, leave it behind. Like I said, treat it as a guide.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
1

Is what I am doing correct?

Considering the following code:

public void OnAuthentication(AuthenticationContext context)
{
  IIdentity ident = context.Principal.Identity;
  if (!ident.IsAuthenticated || !ident.Name == "randy") // Name is just for testing
  {
      context.Result = new HttpUnauthorizedResult();
  }
}

Regardless of the underlying framework, you're mixing authentication with authorization in this specific example.

Why don't the examples in the web just redirect in OnAuthentication if the user is not authenticated. Why wait for OnAuthentication to execute?

Specifically for ASP.Net MVC, and disregarding the Authentication Framework used, Authorization to specific controllers should be controlled using AuthorizeAttribute, of which there are plenty of examples. Keep in mind that whatever Framework you use, roles are available out-of-the-box but the latest and greatest is to use claims instead of roles (AuthorizeAttribute that uses Claims).

If what I am doing is correct, how do I set the Principal from the LogIn Action method? How do I clear it? And if I understand correctly, is this synonymous to logging in/logging out (setting principal/clearing principal)?

Without getting into details about the complicated ASP.Net Pipeline (that MVC has nicely abstracted away for MVC developers so we don't need to use it 99% of the time), there are events that occur when someone sends a request to an IIS web server. The Pipeline and security framework mostly take care of specifics regarding setting the current user authentication and authorization (in terms of roles/claims). One of these is the value of IPrincipal. Under normal and less complicated scenarios you should not ever need to set or remove this value (it is done auto-magically) by the security framework (when you call the frameworks specific methods for logging someone in or out).

If all I am doing is wrong, or even if it is right, could you direct me to where can I start learning authentication for ASP.NET MVC? When I search, the topics are for a specific implementation of something which mostly assumes understanding of some concepts. I'm having a hard time of where to start.

Eventhough the Help clearly states:

Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.

I don't believe that Asp.Net Website will be disappearing anytime soon so the link should be valid for years to come.

Lastly, as with many other technologies, the current ASP.Net Identity (Security Framework) isn't specific to MVC so some examples may not make sense if the context isn't regarding MVC.

Community
  • 1
  • 1
Erik Philips
  • 53,428
  • 11
  • 128
  • 150