2

I have looked at ASP.NET Identity and it looks really complex and difficult to follow. Basically what I want to know is the easiest way to authorize a user on login so the [Authorize] data annotation will allow them through.

Fabio
  • 11,892
  • 1
  • 25
  • 41
TobusBoulton
  • 181
  • 1
  • 14
  • Take a look at this link. It explains forms authentication. http://www.codeproject.com/Articles/578374/AplusBeginner-splusTutorialplusonplusCustomplusF – Nejdi Kroi Aug 19 '15 at 12:48
  • Try to follow this how-to: http://www.ienablemuch.com/2014/10/aspnet-mvc-forms-authentication-in-eight-easy-steps.html – Michael Buen Aug 19 '15 at 12:54

1 Answers1

4

Follow these steps:

Install the following NuGet packages

  • Microsoft.Owin
  • Microsoft.Owin.Host.SystemWeb
  • Microsoft.Owin.Security
  • Microsoft.Owin.Security.Cookies

Inside App_Start folder, add a AuthConfig that look like this:

public static class AuthConfig
{
    public const string DefaultAuthType = "DefaultAppCookie"; //example
    public const string LoginPath = "System/SignIn"; //example

    public static void ConfigureAuth(IAppBuilder app)
    {
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthType,
            LoginPath = new PathString(LoginPath)
        });
    }
}

In the root path of the project, add a Startup.cs that look like this

[assembly: OwinStartup(typeof(YourPorject.Startup))]
namespace YourPorject
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            AuthConfig.ConfigureAuth(app);
        }
    }

}

To authenticate an user (usually inside a Login Action):

//user = the user that is loggin on, retrieved from database 
List<Claim> claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, user.Name),
                new Claim(ClaimTypes.Email, user.Email),
                //some other claims
            };

ClaimsIdentity identity = new ClaimsIdentity(claims, AuthConfig.DefaultAuthType);
IAuthenticationManager authManager = Request.GetOwinContext().Authentication;
authManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);

You need to add a ClaimTypes.Role to authorize specific roles.

Fabio
  • 11,892
  • 1
  • 25
  • 41
  • Thanks for your post. One quick question, what does DefaultAuthType entail? Thanks – TobusBoulton Aug 19 '15 at 13:30
  • 1
    It is just a const string to be used in the Login Action... because the name of the authentication type used in ClaimsIdentity object must match with the AuthConfig – Fabio Aug 19 '15 at 13:34
  • It was extremely difficult to find a complete example for claims and roles being persisted without asp.net identity. Thank you. – Caio Sant'Anna Nov 06 '20 at 02:47